是否有一个 Ruby 习语用于在条件为真时从数组中弹出项目并返回集合?
IE,
# Would pop all negative numbers from the end of 'array' and place them into 'result'.
result = array.pop {|i| i < 0}
据我所知,不存在上述情况。
我目前正在使用
result = []
while array.last < 0 do
result << array.pop
end
是否有一个 Ruby 习语用于在条件为真时从数组中弹出项目并返回集合?
IE,
# Would pop all negative numbers from the end of 'array' and place them into 'result'.
result = array.pop {|i| i < 0}
据我所知,不存在上述情况。
我目前正在使用
result = []
while array.last < 0 do
result << array.pop
end
也许你正在寻找take_while?
array = [-1, -2, 0, 34, 42, -8, -4]
result = array.reverse.take_while { |x| x < 0 }
result将是[-8, -4]。
要取回原始结果,您可以drop_while改用。
result = array.reverse.drop_while { |x| x < 0 }.reverse
result在[-1, -2, 0, 34, 42]这种情况下。
你可以自己写:
class Array
def pop_while(&block)
result = []
while not self.empty? and yield(self.last)
result << self.pop
end
return result
end
end
result = array.pop_while { |i| i < 0 }
如果您正在寻找一种解决方案来弹出所有满足条件的项目,请考虑 aselect后跟 a delete_if,例如
x = [*-10..10].sample(10)
# [-9, -2, -8, 0, 7, 9, -1, 10, -10, 3]
neg = x.select {|i| i < 0}
# [-9, -2, -8, -1, -10]
pos = x.delete_if {|i| i < 0}
# [0, 7, 9, 10, 3]
# note that `delete_if` modifies x
# so at this point `pos == x`