Could somebody please explain why the variable named foo remains true in the code below, even though it’s set to false when the method is called? And why the symbol version behaves as expected?
def test(options = {})
foo = options[:foo] || true
bar = options[:bar] || :true
puts "foo is #{foo}, bar is #{bar}"
end
>> test(:foo => false, :bar => :false)
foo is true, bar is false
I’ve only tried this using Ruby 1.8.7.
The line
with
options[:foo]beingfalsecould be rewritten asand that is clearly
true.The operator
||can only be used as an “unless defined” operator when the first operator will take a false value (e.g.nil) when not defined. In your casefalseis a defined value, so you can’t use||the way you do. Try rewriting it this way:That will return the value of the
:fookey, ortrueif it’s not set.