Possible Duplicate:
What does ||= mean in Ruby?
I'm new to ruby and I saw this being used in one of the answers here:
RACK_ENV = ENV['ENVIRONMENT'] ||= 'test'
I couldn't find any reference to the ||=
operator...
Possible Duplicate:
What does ||= mean in Ruby?
I'm new to ruby and I saw this being used in one of the answers here:
RACK_ENV = ENV['ENVIRONMENT'] ||= 'test'
I couldn't find any reference to the ||=
operator...
here is the article which explains it really good.
« Ruby, concurrency,... | Main | How does one update... » The curious case of the Ruby T-Square operator. By prashant on Dec 14, 2008 The "||=" operator is interesting, both in what it does as much as in how it's widely used in Ruby land. The operator does not do what you would usually expect. i.e.,
a ||= expr
is not the same as
a = a || expr
The evaluation happens to be
a or a = expr
and the difference is important in at least one use case [0]
As a little DTrace script will verify, this operator is not implemented is a method(or anywhere in Ruby land) and is intrinsic to the VM. The reason is performance, and the fact that the entire expression does not have to be evaluated to yield a result when you're 'OR'ing:
"Ruby's Boolean operators are built into the language and are not based on methods: classes, for example, cannot define their own && method. Ruby defines special true and false values but does not have a Boolean type. method. The reason for this is that Boolean operators can be applied to any value and must behave consistently for any kind of operand."
. . .
"Another reason that Ruby's Boolean operators are a core part of the language rather than redefinable methods is that the binary operators are "short-circuiting." If the value of the operation is completely determined by the lefthand operand, then the righthand operand is ignored and is never even evaluated."
https://blogs.oracle.com/prashant/entry/the_ruby_t_square_operator
what does || do? If you have a and b then a || b
is true if and only if either a or b is true. It is the same with ||= this operator combines two operations '=' and '||'. So a ||= b
is equivelent to c || c = b
EDIT: so in your context ENV['ENVIRONMENT'] ||= 'test' means that if ENV['ENVIRONMENT'] is not nil and not false it will preserve its value, otherwise it will become 'test' and after that the new value of ENV['ENVIRONMENT'] is assigned to RACK_ENV