Christopher Neylan
Christopher Neylan

Reputation: 8272

respond_to?() from top level of script

I can use respond_to?() from the main object in irb:

irb(main):001:0> def foo
irb(main):002:1>   "hi"
irb(main):003:1> end
=> nil
irb(main):004:0> respond_to?(:foo)
=> true
irb(main):005:0> self
=> main

But when I put this into a script, it doesn't seem work as I'd expect:

$ cat test.rb
#! /usr/local/bin/ruby
def foo
  "hi"
end
puts respond_to?(:foo)
puts self

$ ./test.rb
false
main

What's going on here?

EDIT:

The irb behavior works for me in 1.9.3, but not in 2.2.0. But regardless, is it possible to use respond_to?() as such from a script?

As an alternative, I can catch a NoMethodError from a call to send(), but that would also catch such exceptions from inside a valid method as well, which makes error handling a little convoluted.

Upvotes: 2

Views: 130

Answers (1)

infused
infused

Reputation: 24337

Methods defined at the top level are made private methods of Object and by default respond_to? only returns true for public methods. To check for private and protected methods, set the include_all argument to true:

def foo
  "hi"
end 

puts respond_to?(:foo, true)
puts self

Now when the script is run, respond_to?(:foo, true) should return true:

$ ./test.rb
true
main

Upvotes: 3

Related Questions