ruby - respond_to?() from top level of script -
i can use respond_to?() 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 put script, doesn't seem work 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 me in 1.9.3, not in 2.2.0. regardless, possible use respond_to?() such script?
as alternative, can catch nomethoderror
call send()
, catch such exceptions inside valid method well, makes error handling little convoluted.
methods defined @ top level made private methods of object
, default respond_to?
returns true public methods. check private , protected methods, set include_all
argument true:
def foo "hi" end puts respond_to?(:foo, true) puts self
now when script run, respond_to?(:foo, true)
should return true:
$ ./test.rb true main