# explanation of method

hey i have a method

logged_in? && authorized? ? true : access_denied
end

this is from an authentication plugin. i cant make sense of it, and
dont understand wot the '||=' symbol does. i cant google for it, cos
google strips the search for the symbol. can someone explain step by
step wot the function is doing ?

This is a ruby question so probably better suited to other places, but anyway,
for most operators
a op= b is the same as a = a op b
So a ||= b is the same a = a || b
Because of the way ruby evaluates these things, it means set a to b unless a is already set (in which case it won't even evaluate b).

Fred

Hi --

hey i have a method

>> :false if username && passwd
logged_in? && authorized? ? true : access_denied
end

this is from an authentication plugin. i cant make sense of it, and
dont understand wot the '||=' symbol does. i cant google for it, cos
google strips the search for the symbol. can someone explain step by
step wot the function is doing ?

This is a ruby question so probably better suited to other places, but
anyway,
for most operators
a op= b is the same as a = a op b
So a ||= b is the same a = a || b
Because of the way ruby evaluates these things, it means set a to b
unless a is already set (in which case it won't even evaluate b).

There's at least one edge-case which reveals that it a ||= b and
a = a || b aren't quite the same:

irb(main):007:0> h = Hash.new(1)
=> {}
irb(main):008:0> h[:x] ||= 2
=> 1
irb(main):009:0> h
=> {}

Here's what happens with the plain || version:

irb(main):010:0> h[:y] = h[:y] || 3
=> 1
irb(main):011:0> h
=> {:y=>1}

Matz had something to say about ||= at the Ruby Clinic that I
conducted on Friday at RubyConf -- namely, that it's better to think
of it this way:

x ||= y => x || (x = y)

Translating my example that way produces the right result.

David

You learn something everyday! Thanks for that.

Fred