Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about "respond_to?" method

Tags:

ruby

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?

like image 689
MichaelHajuddah Avatar asked Jul 27 '13 03:07

MichaelHajuddah


3 Answers

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
like image 185
Victor Deryagin Avatar answered Oct 22 '22 23:10

Victor Deryagin


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)

like image 4
Redserpent Avatar answered Oct 22 '22 23:10

Redserpent


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.

like image 3
ChrisPhoenix Avatar answered Oct 22 '22 23:10

ChrisPhoenix