Is the ruby operator ||= intelligent?
This is extremely easy to test:
class MyCache
def initialize
@hash = {}
end
def []=(key, value)
puts "Cache key '#{key}' written"
@hash[key] = value
end
def [](key)
puts "Cache key '#{key}' read"
@hash[key]
end
end
Now simply try the ||=
syntax:
cache = MyCache.new
cache["my key"] ||= "my value" # cache value was nil (unset)
# Cache key 'my key' read
# Cache key 'my key' written
cache["my key"] ||= "my value" # cache value is already set
# Cache key 'my key' read
So we can conclude that no assignment takes place if the cache key already exists.
The following extract from the Rubyspec shows that this is by design and should not be dependent on the Ruby implementation:
describe "Conditional operator assignment 'obj.meth op= expr'" do
# ...
it "may not assign at all, depending on the truthiness of lhs" do
m = mock("object")
m.should_receive(:foo).and_return(:truthy)
m.should_not_receive(:foo=)
m.foo ||= 42
m.should_receive(:bar).and_return(false)
m.should_not_receive(:bar=)
m.bar &&= 42
end
# ...
end
In the same file, there is a similar spec for []
and []=
that mandates identical behaviour.
Although the Rubyspec is still a work in progress, it has become clear that the major Ruby implementation projects intend to comply with it.
What does the '||=' operator do in ruby?
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
What does the ||= operand stand for in ruby
It is the shorthand for a logical OR operation. It is equivalent to:
a || a = b
Note: The above code sample has been corrected to reflect the true (if unintuitive) behavior if expanding a ||= b
. Thanks to the people who pointed that out for me. Here is the source
if a
evaluates to true it will remain as is, otherwise b
will be assigned to a
. In ruby nil
evaluates to false
, so you can see how this is useful for lazy loading and default value assignment.
What does ||= mean?
Basically, a ||= b
means assign b to a if a is null or undefined or false (i.e. false-ish value in ruby)
, it is similar to a = b unless a
, except it will always evaluate to the final value of a
(whereas a = b unless a
would result in nil
if a
was true-ish).
'||=' operator in Ruby
It's an assignment operator for 'Conditional Assignment'
See here -> http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Operators
Conditional assignment:
x = find_something() #=>nil
x ||= "default" #=>"default" : value of x will be replaced with "default", but only if x is nil or false
x ||= "other" #=>"default" : value of x is not replaced if it already is other than nil or false
Operator ||= is a shorthand form of the expression:
x = x || "default"
EDIT:
After seeing OP's edit, the example is just an extension of this, meaning:
car = method_1 || method_2 || method_3 || method_4
Will assign the first non-nil or non-false return value of method_1, method_2, method_3, method_4 (in that order) to car
or it'll retain its old value.
What does ||= mean?
It is an assignment operator which means: or assign this value to a variable.
So if you did something like x ||= y
this meansx || x = y
so if x is nil or false set x to be the value of y.
What does ||= do in Ruby 1.9.2?
It assigns []
to params["user][:role_ids]
if params["user][:role_ids]
is nil
or another falsy value...
Otherwise, it retains the original value of params["user][:role_ids]
Example
variable = nil
variable ||= "string"
puts variable # "string"
variable2 = "value"
variable2 ||= "string"
puts variable2 # "value"
Related Topics
Why Are Exclamation Marks Used in Ruby Methods
How to Call Methods Dynamically Based on Their Name
Difference Between "Or" and || in Ruby
How to Pass Command Line Arguments to a Rake Task
Does Ruby Have Real Multithreading
Difference Between Rake Db:Migrate Db:Reset and Db:Schema:Load
What Is the Ruby ≪=≫ (Spaceship) Operator
Why Use Ruby'S Attr_Accessor, Attr_Reader and Attr_Writer
How to Redirect to a 404 in Rails
How to Check Whether a String Contains a Substring in Ruby
Sqlite3-Ruby Install Error on Ubuntu
How to Search Within an Array of Hashes by Hash Values in Ruby
Get Names of All Files from a Folder With Ruby
Is There a Reason That We Cannot Iterate on "Reverse Range" in Ruby