加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby方法()方法

发布时间:2020-12-17 02:41:52 所属栏目:百科 来源:网络整理
导读:我想了解 Ruby方法方法()的工作原理. 我尝试使用“ruby方法”谷歌,但这不是我需要的. 我也见过ruby-doc.org,但我没有找到这种方法. 你能详细说明它的工作原理或给我一个链接吗? 更新 我用methods()方法进行了实验并得到了这样的结果: ‘lab rat’代码 clas
我想了解 Ruby方法方法()的工作原理.
我尝试使用“ruby方法”谷歌,但这不是我需要的.
我也见过ruby-doc.org,但我没有找到这种方法.

你能详细说明它的工作原理或给我一个链接吗?

更新

我用methods()方法进行了实验并得到了这样的结果:

‘lab rat’代码

class First
  def first_instance_mymethod
  end
  def self.first_class_mymethod
  end
end
class Second < First
  def second_instance_mymethod
  end
  def self.second_class_mymethod
  end
end

使用类

#returns available methods list for class and ancestors
puts Second.methods.grep(/mymethod/)
  # => second_class_mymethod
  # => first_class_mymethod

#returns Class methods list for current class only 
puts Second.methods(false)
  # => second_class_mymethod

使用对象

obj = Second.new
def obj.obj_singleton_mymethod
end

#returns available methods list for object and ancestors
puts obj.methods.grep(/mymethod/)
  # => second_instance_mymethod
  # => first_instance_mymethod

#returns current object class methods
puts obj.methods(false)
  # => obj_singleton_mymethod

解决方法

我不完全确定为什么它不在ruby 1.9文档中(它似乎仍然在代码中),但你可以在1.8.7文档中看到文档: http://www.ruby-doc.org/core-1.8.7/classes/Object.html#M000032

基本上,在ruby 1.9中,它只返回给定类及其祖先中所有方法的符号(名称)列表. (ruby 1.8它返回了一个字符串列表)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读