||= in an expression

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 :frowning: )

Can anyone tell me what it means

TiA

On Jul 27, 2006, at 3:10 AM, rejoc wrote:

=" is not of much help :frowning: )

Can anyone tell me what it means

TiA

Consider:

“some string” || “a string”

versus:

nil || “a string”

The former returns “some string”, but the latter returns “a string”.
Apply that to the form you described and it basically means that if a
[:i] is nil then it assigns “a string”, otherwise it leaves it alone.

  • Jake McArthur

On 27/07/06, rejoc [email protected] wrote:

not of much help :frowning: )

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

On 27-Jul-06, at 4:10 AM, rejoc wrote:

=" is not of much help :frowning: )

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 T.
[email protected]

“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

On 7/27/06, rejoc [email protected] wrote:

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

Can anyone tell me what it means

TiA

It is very useful as

var ||= expr

is a shortcut for

var = expr unless defined? var and var

which means if var is defined and evaluates to true it is left alone
however if var is not defined or evaluates to false it is assigned expr.
That means also that
var ||= expr
will overwrite nil and false values in var, a fact which seems to be
overseen sometimes.

Cheers
Robert


Deux choses sont infinies : l’univers et la bêtise humaine ; en ce qui
concerne l’univers, je n’en ai pas acquis la certitude absolue.

  • Albert Einstein

Farrel L. a écrit :

will return anotherObject (assuming it’s value isn’t nil)
nil then it will remain unchanged. If it is nil then it will be set to
“a string”.

Farrel

Thanks a lot.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs