-1

我有一个像这样的数组:
input2 = ["Other", "Y", "X", "Z", "Description"]

我想取下"Y", "X", "Z", "Description"并将它们存储在一个变量中,但保持它们的顺序。
示例:
input2 = ["Z", "X", "Y", "Other", "Description"]我们应该有:

input3 = ["Other"]
some_variable = ["Z", "X", "Y", "Description"]

感谢帮助。

4

4 回答 4

1

就像是?

def get_stuff(arr, *eles) # or change eles from splat to single and pass an array
  eles.map { |e| e if arr.include?(e) }
end

input2 = ["Other", "Y", "X", "Z", "Description"] 

x = get_stuff(input2, 'Y', 'X', 'Z', 'Description')
y = get_stuff(input2, 'Other')
p x
#=> ["Y", "X", "Z", "Description"]
p y
#=> ["Other"]

不是很优雅,但它确实有效。

于 2013-02-06T23:28:25.313 回答
0
input2 = [:a,:b,:c,:d,:e]
input3 = input2.slice!(-4..-1) # ! indicates destructive operator
#Or just as well: input3 = input2.slice!(0..4)
input2.inspect
#[:a]
input3.inspect
#[:b,:c,:d,:e]
于 2013-02-06T23:23:21.067 回答
0
def take_it_off(arr, values)
  without = []
  ordered_values = []
  arr.each do |val|
    if values.include? val
      ordered_values << val
    else
      without << val
    end
  end

  return without, ordered_values
end

所以你可以做

irb> values = "Y", "X", "Z", "Description"
=> ["Y", "X", "Z", "Description"]

irb> arr = ["Z", "X", "Y", "Other", "Description"]
=> ["Z", "X", "Y", "Other", "Description"]

irb> take_it_off(arr, values)
=> [["Other"], ["Z", "X", "Y", "Description"]]
于 2013-02-06T23:44:27.550 回答
0

这实际上可以使用 Ruby 删除方法和地图来完成。可能还可以更简化。

def get_stuff(arr=[], eles=[])
  eles.map { |e| arr.delete(e) }
end

a = %w(Other Y X Z Description)
v = %w(Y X Z Description)
r = get_stuff(a, v)

# a is modified to ["Other"]
# r returns ["Y", "X", "Z", "Description"]
于 2013-02-07T01:27:05.407 回答