Shorthand for "return x if x" in Ruby Shorthand for "return x if x" in Ruby ruby ruby

Shorthand for "return x if x" in Ruby


I'm just about certain that there exists no shorthand for your second example—nor could one be written without modifying the Ruby syntax—since it's not a common enough idiom. Sorry, bro, but it looks like you're going to have to be verbose on this one. (Though, really, as far as verbosity goes, this one isn't all that bad.)

(Note, too, that the first example isn't quite right: x ||= a is equivalent to x = x || a, which can also be expressed as x = a unless x.)


you can omit the return if it is the last statement in a block code.

example

irb(main):002:0> def b(c)irb(main):003:1>   c if cirb(main):004:1> end=> nilirb(main):005:0> b(4)=> 4irb(main):006:0> b(nil)=> nilirb(main):007:0> b(true)=> trueirb(main):008:0> b(false) # TADA!!!=> nil