开发者

Ruby hash value truthiness and symbols

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

foo = options[:foo] || true

with options[:foo] being false could be rewritten as

foo = false || true

and 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 case false is a defined value, so you can't use || the way you do. Try rewriting it this way:

foo = options.fetch(:foo, true)

That will return the value of the :foo key, or true if it's not set.


|| is OR. What you are basically doing is assigning foo to false || true. OR returns true when at least one of the options is true, or false when they're both false.

The truth table of the OR gate is as follows:

INPUT1 | INPUT2 | OUTPUT
   0   |    0   |   0
   0   |    1   |   1
   1   |    0   |   1
   1   |    1   |   1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜