2013-03-14 10 views
7

有條件爲真時從數組中彈出項目並返回集合的Ruby成語嗎?有條件成立時從數組中彈出項目的紅寶石成語

即,

# 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 
+0

更通用;彈出數組末尾的所有匹配項。如果遇到不匹配的項目,請停止。 – 2013-03-14 16:50:20

+1

「不要跳過不匹配」:我無法解析此問題。 – 2013-03-14 16:51:24

+0

我已經改寫過它 – 2013-03-14 16:52:46

回答

7

也許你正在尋找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]

+0

是否有一種take_while的變體也可以從數組中刪除項目? – 2013-03-14 16:54:57

+0

@ComputerLinguist我不這麼認爲。我環顧四周,沒有發現任何東西。 – squiguy 2013-03-14 16:56:43

+2

@ComputerLinguist,在上面相同的上下文中使用'drop_while'將返回原始數組,並刪除那些元素。 I.E. '結果= [-1,-2,0,34,42]' – AGS 2013-03-14 17:04:32

1

你可以自己編寫:

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 } 
+0

是的,但是我真的想找更多的標準/習慣性的東西 – 2013-03-14 17:11:15

+2

有'take_while'和'drop_while'這樣的方法,所以'pop_while'看起來很像它...恐怕沒有東西像紅寶石標準一樣。 – Huluk 2013-03-14 17:24:06

0

如果您尋找一個解決方案,以彈出滿足條件的所有項目,考慮select後跟一個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`