ruby - 如何从数组中删除元素并将它们按顺序保存在变量中?

时间:2013-02-06 23:16:46

标签: ruby-on-rails ruby

我有一个类似的阵列:
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 个答案:

答案 0 :(得分: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"]

真的不优雅,但它有效。

答案 1 :(得分: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]

答案 2 :(得分: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"]]

答案 3 :(得分: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"]