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.
04f4e8457b965e5e03cc44c9cba5fe51?d=identicon&s=25 maggelet (Guest)
on 2005-11-18 21: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.
D8831c4665a164c6ce484003deb1afd6?d=identicon&s=25 guslist (Guest)
on 2005-11-18 21: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.
47b1910084592eb77a032bc7d8d1a84e?d=identicon&s=25 vjoel (Guest)
on 2005-11-18 21: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.
4299e35bacef054df40583da2d51edea?d=identicon&s=25 james (Guest)
on 2005-11-18 21: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 Gray II
04f4e8457b965e5e03cc44c9cba5fe51?d=identicon&s=25 maggelet (Guest)
on 2005-11-18 22:15
(Received via mailing list)
got it, that's what I figured.  Is there a list of these somewhere?
Thanks
4674615d2cf231975c741731be9a8685?d=identicon&s=25 ruby-talk (Guest)
on 2005-11-18 23: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.