[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

||= in an expression

rejoc

7/27/2006 8:06:00 AM

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
3 Answers

Farrel Lifson

7/27/2006 8:18:00 AM

0

On 27/07/06, rejoc <rejoc@freefree.fr> wrote:
> 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

Jeremy Tregunna

7/27/2006 8:19:00 AM

0


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

> 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
jtregunna@blurgle.ca


"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


rejoc

7/27/2006 8:42:00 AM

0

Farrel Lifson a écrit :
> On 27/07/06, rejoc <rejoc@freefree.fr> wrote:
>
> 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.