是否有ruby单行“如果x返回”?

有很多我需要添加的地方

if this_flag return end 

可以用ruby在一行上完成吗?

是否有ruby单行“ return if x ”?

是:

 return if x 

我爱Ruby 🙂

JörgWMittag的一些补充:

 x && return x and return if x then return end 

我实际上并不推荐前两种forms:但是,上面的例子都是有效的产品。 我个人更喜欢一般避免return – Ruby中的大多数语法结构都是可用的表达式。

快乐的编码。

Ruby总是返回最后一件事……为什么不以不同的方式构建代码呢?

 def returner(test) "success" if test end 

无论你最后做了什么,都会回归。 我爱Ruby。

创建一个检查预期类类型的方法示例如下。 方法check_class找到正确的类就会返回true。 如果您因任何原因需要扩展不同类类型的数量,则非常有用。

 def check_class(x) return true if is_string(x) return true if is_integer(x) # etc etc for possible class types return false # Otherwise return false end def is_string(y) y.is_a? String end def is_integer(z) z.is_a? Integer end a = "string" puts "#{check_class(a)}"