How does "|| =" work?

Possible duplicate:
What does the value || = (or equal) in Ruby?

I am learning Ruby and am confused in the following code. I can understand what he is doing, but cannot understand how it works.

h = Hash.new
h['key1'] ||= 'value1'
=> "value1"

p h
=> {"key1"=>"value1"}
0
source share
3 answers

Given Hash:

hash = {}

This expression:

hash[:key] ||= :value

Expands to:

hash[:key] || hash[:key] = :value

Ruby's logical operators are a short circuit , which means it hash[:key] = :valuewill only be executed if and only if it hash[:key]is either falseor nil.

If this is something else, only its value will be sufficient to determine the result of a logical disjunction , and the rest of the expression will not be evaluated.

This is fundamentally different from:

hash[:key] = hash[:key] || :value

[]= , , : :value, hash[:key] false, nil, hash[:key] .

0

. ; :

x += y #expands to x = x+y

||= :

x ||= y expands to x = x||y

+, -,/,%, *, &, ||, &, |, ^, <, → .

-1

Hash.new nil

h['key1'] ||= 'value1' " =" 1 " , " value1 ""

-2

All Articles