1

Ruby 中是否有一种方法可以从 Array (或 other )中删除前n 个Enumerable项目,更改数组变量,并返回数组的剩余元素,而不是被删除的元素?

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

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

a.drop不是我想要的,因为这不会改变a. a.shift也不正确,因为在上面的示例中它将返回["r", "u"]而不是["b", "y"].

4

3 回答 3

2

是的.. 可能使用Object#tapand Array#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"]
于 2013-11-01T07:45:16.363 回答
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"]
于 2013-11-01T08:05:54.693 回答
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(如其他答案中给出的)看起来更加优雅。

于 2013-11-01T08:20:57.173 回答