||= in an expression

R

rejoc

Hello,

I new to Ruby and curious about this language I do use (yeet).

I was browsing through some libraries/modules and I found a line looking
like

a[:i] ||= "a string"

I could not find this syntax in any manual online (and googling "||=" is
not of much help :-( )

Can anyone tell me what it means

TiA
 
F

Farrel Lifson

Hello,

I new to Ruby and curious about this language I do use (yeet).

I was browsing through some libraries/modules and I found a line looking
like

a[:i] ||= "a string"

I could not find this syntax in any manual online (and googling "||=" is
not of much help :-( )

Can anyone tell me what it means

TiA

In Ruby

nil || anObject

will return anObject and

anotherObject || anObject

will return anotherObject (assuming it's value isn't nil)

The expression

a[:i] ||= "a string"

is equivalent to

a[:i] = a[:i] || "a string"

(sort of like 'num+= 1' is the same as 'num = num + 1')If a[:i] is not
nil then it will remain unchanged. If it is nil then it will be set to
"a string".

Farrel
 
J

Jeremy Tregunna

Hello,

I new to Ruby and curious about this language I do use (yeet).

I was browsing through some libraries/modules and I found a line
looking like

a[:i] ||= "a string"

I could not find this syntax in any manual online (and googling "||
=" is not of much help :-( )

Can anyone tell me what it means

it will return the value for a[:i] if a value exists, if not, it will
set a[:i] to the value "a string".

--
Jeremy Tregunna
(e-mail address removed)


"One serious obstacle to the adoption of good programming languages
is the notion that everything has to be sacrificed for speed. In
computer languages as in life, speed kills." -- Mike Vanier
 
R

rejoc

Farrel Lifson a écrit :
In Ruby

nil || anObject

will return anObject and

anotherObject || anObject

will return anotherObject (assuming it's value isn't nil)

The expression

a[:i] ||= "a string"

is equivalent to

a[:i] = a[:i] || "a string"

(sort of like 'num+= 1' is the same as 'num = num + 1')If a[:i] is not
nil then it will remain unchanged. If it is nil then it will be set to
"a string".

Farrel
Thanks a lot.
 

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
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top