Edit: I'm using Ruby version 2.0.0
I have the following code in a file example.rb
def say_hello
puts 'hi'
end
puts respond_to?(:say_hello)
say_hello
When running this code, the output is:
false
hi
I'm confused why false is returned for "respond_to?" when I can use that method.
The "respond_to?" method seems to work this way though:
class Person
def say_bye
puts 'bye'
end
end
mike = Person.new
puts mike.respond_to?(:say_bye)
mike.say_bye
The output is:
true
bye
Does anyone have any insight as to why "respond_to?" returns false in the first case?
Top-level methods are defined as private, and Object#respond_to?
ignores private methods by default (you need to pass second argument for it to recognize say_hello
):
def say_hello
puts 'hi'
end
puts respond_to?(:say_hello) #=> false
puts respond_to?(:say_hello, :include_private) #=> true
say_hello
In Ruby .respond_to? A check method for Ruby, not Rails which has respond_to
Takes a symbol and returns true if an object can receive that method, else it returns a false
Your first code has a missing dot(.) before respond_to? ... when I ran it printed hi but had no confirmation of true condition.
Syntax: object.respond_to?(:method)
--> [1,2,3,5,8,13].respond_to?(:push)
This one took a lot of digging.
As explained here, http://marakana.com/bookshelf/ruby_tutorial/scope.html near the bottom: "methods defined outside any class or module become private methods on Object and are available everywhere."
self, at top-level in a file, is a special thing called 'main'.
Now here's the funny part. Objects deny that they respond to private methods.
... the other answer has the rest of the info.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With