In-line if statement with parentheses vs without parentheses

I’m relatively new to Ruby, and when I was reading this post
http://tmm1.net/ruby21-profiling/ I came across something I did not
understand.

Towards the end he explains that he was able to decrease
method calls to present? by 40% just by making this subtle change:

def owner

  • @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?

On Friday, January 3, 2014, Joe O. wrote:

  • @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.

On Fri, Jan 3, 2014 at 6:39 PM, Joe O. [email protected] wrote:

  • @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.

John

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.

| Privacy Policy | Terms of Service | Remote Ruby Jobs