2013-10-31 193 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