如何在Ruby中找出方法所属的类?

时间:2011-10-29 05:37:12

标签: ruby

如何在Ruby中找出定义方法的类?

例如,假设我想知道哪些类实现了to_s方法。我如何使用ri命令执行此操作?

3 个答案:

答案 0 :(得分:1)

~$ ri

Enter the method name you want to look up.
You can use tab to autocomplete.
Enter a blank line to exit.

>> to_s

= .to_s

(from gem actionpack-3.1.0.rc6)
=== Implementation from ActionDispatch::RemoteIp::RemoteIpGetter
------------------------------------------------------------------------------
  to_s()

------------------------------------------------------------------------------


(from gem actionpack-3.1.0.rc6)
=== Implementation from ActionView::FileSystemResolver
------------------------------------------------------------------------------
  to_s()

------------------------------------------------------------------------------


(from gem actionpack-3.1.0.rc6)
=== Implementation from ActionView::FixtureResolver
------------------------------------------------------------------------------
  to_s()

答案 1 :(得分:1)

编辑|这个答案没有任何意义,因为你编辑了你的问题;)脱离了它的背景。

非常无效的方法。我个人无法理解为什么你需要这个:

class ClassEnumerator
  def each(&block)
    ObjectSpace.each_object(Class, &block)
  end

  include Enumerable
end

ClassEnumerator.new.select { |klass| klass.instance_methods.include?(:merge) }

这应该找到所有实现#merge的类。

pry(main)> ClassEnumerator.new.select { |klass| klass.instance_methods.include?(:merge) }
=> [OptionParser::CompletingHash,
 OptionParser::OptionMap,
 Hash,
 Gem::Dependency,
 Psych::Omap,
 Psych::Set,
 URI::MailTo,
 URI::LDAPS,
 URI::LDAP,
 CodeRay::CaseIgnoringWordList,
 CodeRay::WordList,
 URI::HTTPS,
 URI::HTTP,
 URI::FTP,
 URI::Generic]
pry(main)> 

答案 2 :(得分:0)

您也可以输入ri METHOD_NAME,然后点击man ri