Ruby:从Array的开头就地放置元素并返回剩余的数组

时间:2013-11-01 07:43:11

标签: ruby arrays enumerable

Ruby中是否有方法从数组(或其他Enumerable)中删除第一个 n 项,更改数组变量,并返回剩余数组的元素,而不是被删除的元素?

基本上我正在寻找这样的东西:

a = ["r", "u", "b", "y"]
a.mystery_function!(2)
# => ["b", "y"]
puts a
# => ["b", "y"]

a.drop不是我想要的,因为它不会改变a的价值。 a.shift不正确,如上例所示,它会返回["r", "u"]而不是["b", "y"]

3 个答案:

答案 0 :(得分:2)

是..可以使用Object#tapArray#shift

a = ["r", "u", "b", "y"]
p a.tap{|i| i.shift(2)}
# >> ["b", "y"]
p a
# >> ["b", "y"]

如果你想修补类Array。

class Array
  def mystery_function!(n)
     shift(n);self
  end
end
a = ["r", "u", "b", "y"]
p a.mystery_function!(2)
# >> ["b", "y"]
p a
# >> ["b", "y"]

答案 1 :(得分:1)

a = ["r", "u", "b", "y"]
a.replace(a.drop(2)) # => ["b", "y"]
a # => ["b", "y"]

或者,也许你可以定义一个:

class Array
  def drop! n; replace(drop(n)) end
end

a = ["r", "u", "b", "y"]
a.drop!(2) # => ["b", "y"]
a # => ["b", "y"]

答案 2 :(得分:0)

因为你想从数组的开头删除它,它可以是

a = ["r", "u", "b", "y"]
a.each_with_index{ |v,i| a.delete_at(0) if i < 2 }  #=> 2 is the no.of elements to be deleted from the beginning.    
=> ["b", "y"]

把所有东西都放到位......

class Array
  def mystery_function!(x=nil)
    each_with_index{ |v,i| delete_at(0) if i < x }
  end
end

a = ["r", "u", "b", "y"]
a.mystery_function!(2)
puts a #=> ["b", "y"]

说完上述内容后,我觉得使用shift(在其他答案中给出)看起来更优雅。