Sunday, May 30, 2010

Nil-coalescing in Ruby

In Ruby, you can check if an object is nil with the nil? method:

if @foo.nil? then
    @foo =

But this can be shortened via the || operator:

@foo = @foo ||

Better yet, we can shorten it even more with the ||= operator:

@foo ||=

Both the above assignments assign to @foo if and only if @foo is nil or false, else leave @foo as it is.