Vaguely about "reply_to?" method

Edit: I am using Ruby version 2.0.0

I have the following code in example.rb file

def say_hello puts 'hi' end puts respond_to?(:say_hello) say_hello 

When running this code, the output is:

 false hi 

I am confused why false is returned for "reply_to?" when can i use this method.

"reply_to?" the method seems to work this way:

 class Person def say_bye puts 'bye' end end mike = Person.new puts mike.respond_to?(:say_bye) mike.say_bye 

Output:

 true bye 

Does anyone have an idea why "reply_to?" returns false in the first case?

+6
source share
3 answers

Top-level methods are defined as private, and Object#respond_to? ignores private methods by default (you need to pass a second argument so that it recognizes say_hello ):

 def say_hello puts 'hi' end puts respond_to?(:say_hello) #=> false puts respond_to?(:say_hello, :include_private) #=> true say_hello 
+11
source

In Ruby .respond_to? Validation method for Ruby, not Rails, which has reply_to
It takes a character and returns true if the object can get this method, else it returns false

Your first code does not have a dot ( . ) Before the_to answer? ... when I ran it, printed hi , but did not receive a confirmation of the true state.

Syntax: object.respond_to? (: method)

-> [1,2,3,5,8,13]. Does it fit? (: push)

+4
source

It took up a lot of space.

As explained here, http://marakana.com/bookshelf/ruby_tutorial/scope.html below: "Methods defined outside of any class or module become private methods in Object and are available everywhere."

self, at the top level in the file, this is a special thing called "main".

Now here is the funny part. Objects deny that they respond to private methods.

... another answer contains the rest of the information.

+3
source

Source: https://habr.com/ru/post/950407/


All Articles