The "|| nil" is redundant in this case.
Basically, ||= is shorthand for
@country = @current_user.country unless @country
aka, set the variable if the variable is currently 'nil'
Jason
The "|| nil" is redundant in this case.
Basically, ||= is shorthand for
@country = @current_user.country unless @country
aka, set the variable if the variable is currently 'nil'
Jason
= is pretty confusing to many people
x ||= y expands to x or x = y
It is fairly simple unless x in a hash or array, then it gets hairy.
Here is David Black's discussion on the topic http://dablog.rubypal.com/2008/3/25/a-short-circuit-edge-case
For a really drawn out discussion and lots of arguing go here: http://groups.google.com/group/comp.lang.ruby/browse_thread/thread/fe4fbc48e19105cd/bf7f73380e285aff?lnk=gst&q=or+equal#bf7f73380e285aff
regards
Here's a more verbose translation:
if x.nil? or x == false then x = y else x end
(Both of those alternatives return the value in x--the first one after the assignment from y.)
Usually what's meant is "give me the value in x, if there is one, but if x is nil, then first assign whatever's in y to x, and *then* give me the value in x". So this method in one of my models:
def self.get_list @@all_organizations ||= self.find(:all, :select => 'id, name') end
Will only hit the database once. After the first time, @@all_organizations won't be nil and ruby will just return the list previously fetched.