2013-10-31 194 views
1

我在做這樣的事情返回真/假塊中的:如何紅寶石

myarray.delete_if{ |x| 
    #some code 
    case x 
    when "something" 
     return true 
    when "something else" 
     return false 
    end 

「返回」聲明似乎錯了,我無法找出正確的語法,我明白了簡單形式:myarray.delete_if{ |x| x == y },但不是當我的願望返回真/假更像程序性的案例陳述的例子。

+1

'myarray - [「something」]' –

回答

4

只需刪除return。在Ruby中,最後一個評估值用作返回值。

myarray = ["something", "something else", "something"] 
myarray.delete_if { |x| 
    #some code 
    case x 
    when "something" 
    true 
    when "something else" 
    false 
    end 
} 
myarray # => ["something else"] 

如果您想明確說明,您可以使用next

1

您無需特別注意false個案。默認情況下,它們可以是nil,如果您不調整它們。

myarray.delete_if do |x| 
    ... 
    case x 
    when "something" then true 
    end 
end 

甚至更​​好:

myarray.delete_if do |x| 
    ... 
    "something" === x 
end 

我不知道你在...部分,但如果你只是想從數組中刪除某個元素,你可以這樣做:

myarray.delete("something") 

,如果你想回到接收器,然後:

myarray.tap{|a| a.delete("something")} 
+0

要完全確切地說,'case'語句通過調用case對象上的'#==='方法來工作。因此,在你的風格中精確地重現OP的代碼行爲的簡短方法是:'a.delete_if&「something」.method(:===)' –

+0

@BorisStitnicky看起來OP好像有一些預處理要做條件/案例聲明。 – sawa