@owner ||= User.find_by_login(params[:user_id]) if
params[:user_id].present?
@owner ||= (User.find_by_login(params[:user_id]) if
params[:user_id].present?)
end
What’s going on here? How are these executed differently?
The first form is saying, if we got a uid, then check if the owner is
nil,
and if so, find the user and assign it as owner. The second reverses
those
two checks. The trick is that in the first form, the “if” applies to
the
entire statement, not just the find.
@owner ||= (User.find_by_login(params[:user_id]) if
params[:user_id].present?)
end
What’s going on here? How are these executed differently?
Order of operations - in the first example the if statement is fired
first
then the ||= and then find_by_login
Second one evaluates the ||= first then the if statement then the
find_by_login.
In both cases if either the ||= or the if statement make the rest of the
calls moot it stops.
So in essence - the ||= call stops the process 40% of the time and
therefore it was stopping the if statement from firing. Basically
identifying whether or not the @owner variable has a value (||=) is the
cheapest operation so you should perform that first.
So in essence - the ||= call stops the process 40% of the time and
therefore it was stopping the if statement from firing. Basically
identifying whether or not the @owner variable has a value (||=) is the
cheapest operation so you should perform that first.
John
Ah, okay! Thanks, John and Dave!
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.