对“respond_to?"感到困惑方法 [英] Confused about "respond_to?" method

查看:38
本文介绍了对“respond_to?"感到困惑方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Ruby 2.0.0 版

I'm using Ruby version 2.0.0

我在文件 example.rb 中有以下代码

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

我很困惑为什么respond_to"返回 false?当我可以使用该方法时.

I'm confused why false is returned for "respond_to?" when I can use that method.

respond_to?"方法似乎是这样工作的:

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

输出为:

true
bye

有没有人知道为什么要respond_to"?在第一种情况下返回 false?

Does anyone have any insight as to why "respond_to?" returns false in the first case?

推荐答案

顶级方法定义为私有,Object#respond_to?默认忽略私有方法(需要传递第二个参数让它识别say_hello):

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

这篇关于对“respond_to?"感到困惑方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆