Forum: Ruby ruby's weird operators (||=)

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
maggelet (Guest)
on 2005-11-18 22:18
(Received via mailing list)
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.
guslist (Guest)
on 2005-11-18 22:24
(Received via mailing list)
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 <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.
vjoel (Guest)
on 2005-11-18 22:24
(Received via mailing list)
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.
james (Guest)
on 2005-11-18 22:27
(Received via mailing list)
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
maggelet (Guest)
on 2005-11-18 23:15
(Received via mailing list)
got it, that's what I figured.  Is there a list of these somewhere?
Thanks
ruby-talk (Guest)
on 2005-11-19 00:22
(Received via mailing list)
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
This topic is locked and can not be replied to.