lampShade
lampShade

Reputation: 4391

How can I find out what class(es) a method is in, in Ruby?

How can I find out what class(es) a method is defined in, in Ruby?

For example lets say that I wanted to know what classes implement the to_s method. How would I do that using the ri command?

Upvotes: 1

Views: 155

Answers (3)

d11wtq
d11wtq

Reputation: 35318

EDIT | This answer makes no sense since you edited your question ;) Out of context it did.

Terribly in-efficient approach. I can't see why you'd need this, personally:

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

  include Enumerable
end

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

This should find all classes implementing #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)> 

Upvotes: 2

user266647
user266647

Reputation:

You can also type ri METHOD_NAME see man ri

Upvotes: 0

Spyros
Spyros

Reputation: 48706

~$ 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()

Upvotes: 1

Related Questions