我想了解一下Ruby方法methods()是如何工作的。
我试着用"ruby方法“搜索谷歌,但这不是我需要的。
我也看过ruby-doc.org,但我没有找到这个方法。
你能向我详细解释它是如何工作的吗?或者给我一个链接?
更新
我尝试了methods()方法,得到了这样的结果:
‘'lab’代码
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发布于 2011-07-20 20:32:02
我不完全确定为什么Ruby1.9文档中没有它(它似乎仍然在代码中),但是您可以在1.8.7文档中看到文档:http://www.ruby-doc.org/core-1.8.7/classes/Object.html#M000032
基本上,在Ruby1.9中,它只返回给定类及其祖先中所有方法的符号(名称)列表。(ruby 1.8返回了一个字符串列表)
发布于 2011-07-20 21:15:20
公认的答案漏掉了一点。在keymone的评论中给出了更完整的答案- .methods返回一个符号数组,这些符号是在给定实例上定义的所有方法的名称。例如:
irb(main):012:0> object = ""
=> ""
irb(main):013:0> object.instance_eval("def foo;:bar;end")
=> nil
irb(main):014:0> object.methods.include?(:foo)
=> true
irb(main):016:0> "".methods.include?(:foo)
=> false发布于 2019-08-13 20:17:30
我使用的是Ruby 2.2.5,不幸的是,当传递false时,我不能再让它工作了。我确实记得在老版本的Ruby中,将false传递给这个方法,用于只返回类级别的方法。
然而,从Ruby 2.2.5开始,我得到了以下结果
class Thingy < ApplicationRecord
def hello
end
end
class Apple < Thingy
def self.goodbye
end
def booty
end
end结果:
2.2.5 :001 > a = Thingy.new
=> #<Thingy id: nil, created_at: nil, updated_at: nil>
2.2.5 :002 > a.methods(false)
=> []
2.2.5 :003 > b = Apple.new
=> #<Apple id: nil, created_at: nil, updated_at: nil>
2.2.5 :004 > b.methods(false)
=> []
2.2.5 :005 > Apple.methods(false)
=> [:attribute_type_decorations, :_validators, :defined_enums, :goodbye]
2.2.5 :006 > Thingy.methods(false)
=> [:attribute_type_decorations, :_validators, :defined_enums]
2.2.5 :007 > 唯一一次传递false返回任何我感兴趣的东西是只检查类级别的方法(那些以self.开头的方法),否则它似乎没有任何帮助。
https://stackoverflow.com/questions/6761651
复制相似问题