Hi there,
Can someone explain to me how the && operator works (in simple terms -
I'm a Ruby newbie! (That even rhymes!
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
ยทยทยท
--
Posted via http://www.ruby-forum.com/ .
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.
ยทยทยท
On Fri, Feb 10, 2012 at 12:38 PM, Phil Carter <pcarter42@gmail.com> wrote:
Hi there,
Can someone explain to me how the && operator works (in simple terms -
I'm a Ruby newbie! (That even rhymes!
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
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
ยทยทยท
--
Posted via http://www.ruby-forum.com/ .
Robert_K1
(Robert K.)
10 February 2012 12:59
4
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
ยทยทยท
On Fri, Feb 10, 2012 at 1:18 PM, Phil Carter <pcarter42@gmail.com> wrote:
Brilliant! That really helps, the bit I was missing is that it returns
the last operand if both are truthy, not immediately obvious.
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/