ruby's weird operators (||=)

M

mark

Hi,
Is there an explanation somewhere of all the weird operators in ruby
such as ||= and exactly what they do?
Apologies if this is a faq but I'm unable to google anything.
 
G

Guillaume Marcais

Hi,
Is there an explanation somewhere of all the weird operators in ruby
such as ||= and exactly what they do?
Apologies if this is a faq but I'm unable to google anything.



a <op>= b

is completely equivalent to

a = a <op> b

So a ||= b means a = a || b. a || b evaluates to a if a is not nil or
false and to b otherwise. The side effect is that a is unchanged if not
nil or equal to b otherwise.

One great use for it is default value assignment:

@a ||= a_default_value

@a is assigned the default value if a has no value yet (nil).

HTH,
Guillaume.
 
J

Joel VanderWerf

mark said:
Hi,
Is there an explanation somewhere of all the weird operators in ruby
such as ||= and exactly what they do?
Apologies if this is a faq but I'm unable to google anything.

Operators of that form are not methods or primitives. This

x ||= 3

is equivalent to

x = x || 3

The r.h.s. has value 3 if x is undefined or nil or false.
 
J

James Edward Gray II

Hi,
Is there an explanation somewhere of all the weird operators in ruby
such as ||= and exactly what they do?
Apologies if this is a faq but I'm unable to google anything.

Anything of the form:

x OP= y

is translated by Ruby to:

x = x OP y

Hope that helps.

James Edward Gray II
 
G

Gene Tani

mark said:
thanks, why

If you still want to Google, this is usually called augmented
assignment (or reflexive assignment, or abbreviated assignment in Matz'
ruby nutshell, which is still a good thing to carry around with you for
stuff like this). In general, i don't know how you come up with Google
search terms, unless you know what they're called in perl or C or
whatever.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,197
Messages
2,571,040
Members
47,634
Latest member
RonnyBoelk

Latest Threads

Top