Ruby: check for nil and initialize on one line

Obviously you could do this:

if(var.nil?)

  var = set_to_something

end

but here’s how to check for nil and initialise on a single line:

var = set_to_something if var.nil?

You could use the ||= operator:

var ||= set_to_something

but it’s a little idiomatic and there are some subtleties involved. More on the Double Pipe / Or Equals operator here:

http://www.rubyinside.com/what-rubys-double-pipe-or-equals-really-does-5488.html

See also:

http://www.rubyfleebie.com/check-for-nil-and-initialize-on-a-single-line/

Leave a Reply

Your email address will not be published. Required fields are marked *