Ruby's weird operators (||=)


#1

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.


#2

On Sat, 2005-11-19 at 05:17 +0900, mark wrote:

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 = b

is completely equivalent to

a = a 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.


#3

mark wrote:

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.


#4

On Nov 18, 2005, at 2:17 PM, mark wrote:

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 G. II


#5

got it, that’s what I figured. Is there a list of these somewhere?
Thanks


#6

mark wrote:

got it, that’s what I figured. Is there a list of these somewhere?
Thanks

Here you go: http://rubygarden.org/ruby?FunnySymbolsInCode

Hi, welcome to the scene, mark.

_why