2

Say I have the following:

class Foo
  def inspect
    false
  end

  def ==(other)
    false == other
  end
end

foo = Foo.new  # => false
foo            # => false
foo == false   # => true
foo == true    # => false

However

if foo then 'hi' end
# => 'hi'

What I was expecting was

if false then 'hi' end
# => nil

I was expecting foo to evaluate as false but it's not. How is if evaluating foo and why is it not false?

4

1 回答 1

7

Only two objects in Ruby are considered to be "falsy": false (of FalseClass) and nil (of NilClass). You can't make another object mimic one of these, because Ruby runtime checks for these two concrete instances.

In your example, you have an instance of the Foo class. It is not false or nil, so it is considered "truthy". There's no way to make it evaluate as falsy value.

于 2013-06-25T11:30:45.140 回答