Sometimes, you want to initialize a variable to some value only if that variable is equal to nil. If you like to write your methods as short, clean and readable as possible, you can do that task in a single line instead of taking the traditionnal 3 lines approach. You have two options :
1) You can use the if modifier
x = get_some_object if x.nil?
Very easy to read. This is my favorite.
2) Or you can use the ||= operator
x ||= get_some_object
This one is even shorter. The ||= operator is a little bit less verbose and might confuse a ruby newcomer… but I’m not saying that it should be a reason for not using it. This is more a matter of personal taste than anything else.
Both of these methods are better than this :
#eeww... we don't like this one. if(x.nil?) x = get_some_object end
9 thoughts on “Check for nil and initialize on a single line”
I always forget there’s a nil? message, usually I do the ||=.
Just curious, what’s a fleebie?
Fleebie is nothing really. I just thought that it would be memorable. =)
There was a squirrel in some weird humor show. I don’t recall how they called it exactly, but it somewhat sounded like “ruby fleebie”.
I would have prefered to tell you another reason…
Something that I find odd about the nil? method is the differentiation between an object being nil and the non-existence of an object. They are not the same. Consider:
>> puts x = 1 if x.nil?
>> puts ‘z is not defined’ if z.nil?
=> NameError: undefined local variable or method ‘z’
How is that explained? In the first instance, the nil? method is obviously creating the x object, assigning nil to it, and then assigning the value 1. In the second instance, nil? is not creating the z object and thus returning an error.
Zerohalo, that’s a very good observation.
Part of the answer is because “=” binds higher than the if modifier. So, in your first example, x is assigned before the condition is executed. That’s why ruby doesn’t complain.
However, I’m not sure about the rest of the story. I GUESS that a nil object is assigned to x at this exact moment and NOT the fixnum 1. Otherwise the if modifier would always returns false…
Frank, since I was curious, I posted the question on the Ruby mailing list, and found the answer. In brief, Ruby sees x and figures it must refer to a variable and therefore creates that variable x, assigning nil value to it, before running x.nil? In the second instance, since the first reference to z is z.nil? and therefore Ruby assumes z is a method rather than variable, does nothing, and therefore z.nil? throws and exception.
Very interesting… I read the post you are relating to and it’s not too far away from what I was thinking.
The difference between
1) x = get_some_object if x.nil?
2) x ||= get_some_object
is that in the first instance x will get reassigned only when it’s nil, while in the second it will get reassigned if it’s nil or false.
Something to know, just in case.
good catch Chris