I don’t understand the following syntax, the “||=” and “||nil”
@country ||= (@current_user.country || nil)
anybody could explain please ?
I don’t understand the following syntax, the “||=” and “||nil”
@country ||= (@current_user.country || nil)
anybody could explain please ?
“@current_user.country || nil” would return the @current_user.country
value if it is not false and nil if it is.
“@country ||= (@current_user.country || nil)” would return the value
of @country if it is not nil and the result of the above example if it
is.
It’s like writing "@country = @country || (@current_user.country ||
nil) " but nicer.
On Jun 13, 7:22 pm, Victor D. [email protected]
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
On Fri, Jun 13, 2008 at 2:22 PM, Victor D.
||= 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.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs