Ruby: check for nil and initialize on one line

Obviously you could do this:


  var = set_to_something


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:

See also:

Leave a Reply

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