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 = Foo.new
end

But this can be shortened via the || operator:

@foo = @foo || Foo.new

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

@foo ||= Foo.new

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