Search code examples
rubyobjectshort-circuitingrespond-to

Ruby 1.9.2 Object.respond_to? :hello && Object.hello gives error, why?


While stepping through code today, I noticed something unexpected. This statement:

if Object.respond_to? :hello && Object.hello #stuff

gives an undefined method error. But why? Obviously hello is not a valid method of Object, however given the short-circuit evaluation, shouldn't Object.hello be ignored whenever Object.respond_to? :hello is false?

I noticed this while playing with Authlogic, trying to figure out exactly why the UserSession class must define persisted? in Rails 3.

Thanks


Solution

  • The lack of parentheses is leading to a precedence issue:

    >> Object.respond_to? :hello && Object.hello
    NoMethodError: undefined method `hello' for Object:Class
        from (irb):2
        from /Users/john/.rvm/rubies/ruby-1.9.2-p136/bin/irb:16:in `<main>'
    >> Object.respond_to?(:hello) && Object.hello
    => false