开发者

How can I nest this if/else as per Ruby?

开发者 https://www.devze.com 2022-12-17 16:33 出处:网络
I want to do this in ruby: something() if conditional else something_else() This doesn\'t compile, nor anything similar from what I tried. Is it possible to have statements in thi开发者_如何学编程s

I want to do this in ruby:

something() if conditional else something_else()

This doesn't compile, nor anything similar from what I tried. Is it possible to have statements in thi开发者_如何学编程s format or do I have to do this as:

if conditional
  something()
else
  something_else()
end


Unfortunately, I know of no way to have both an if and else without putting the condition first. You can do it in one line, though:

if conditional then something else something_else end

or

conditional ? something : something_else


Because Ruby is awesome and doesn't treat statements differently than expressions, mckeed's 2nd answer works perfectly:

conditional ? something : something_else
0

精彩评论

暂无评论...
验证码 换一张
取 消