How does && work in ruby

Hi there,

Can someone explain to me how the && operator works (in simple terms -
I’m a Ruby newbie! (That even rhymes! :wink:

More specifically, why does this piece of code assign a user object (or
nil) to @current_user, not true or false?

@current_user = current_user_session && current_user_session.user

Thanks,

Phil

On Fri, Feb 10, 2012 at 12:38 PM, Phil C. [email protected]
wrote:

Hi there,

Can someone explain to me how the && operator works (in simple terms -
I’m a Ruby newbie! (That even rhymes! :wink:

More specifically, why does this piece of code assign a user object (or
nil) to @current_user, not true or false?

@current_user = current_user_session && current_user_session.user

It’s the “and” operator. It evaluates from left to right its operands,
stopping when one of them is falsy (nil or false). The fact that it
stops when it finds the first value that will render the whole
expression false is called “short circuit”. If all operands are truthy
(not nil nor false) it returns the last operand. The above line is
(roughly) equivalent to:

@current_user = current_user_session.nil? ? nil :
current_user_session.user

I said roughly because it’s different if current_user_session is
false, but due to the usage I would guess that the intent was to check
for nil only.

Jesus.

Brilliant! That really helps, the bit I was missing is that it returns
the last operand if both are truthy, not immediately obvious.

Thanks,

Phil

On Fri, Feb 10, 2012 at 1:18 PM, Phil C. [email protected]
wrote:

Brilliant! That really helps, the bit I was missing is that it returns
the last operand if both are truthy, not immediately obvious.

There is also Enumerable#all? which works similarly (i.e. short
circuit) but will evaluate the block as criterion:

irb(main):010:0> e = [1,2,3]
=> [1, 2, 3]
irb(main):011:0> e.all? {|x| x > 0}
=> true
irb(main):012:0> e.all? {|x| p x; x > 0}
1
2
3
=> true
irb(main):013:0> e.all? {|x| x > 1}
=> false
irb(main):014:0> e.all? {|x| p x; x > 1}
1
=> false

There’s also Enumerable#any? which has OR logic.

irb(main):018:0> e.any? {|x| p x;x > 1}
1
2
=> true

Kind regards

robert

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