Class: Object

Inherits:
BasicObject
Defined in:
lib/methodfinder.rb

Instance Method Summary collapse

Instance Method Details

#find_method(*args, &block) ⇒ Object

An alternative interface to the functionality of MethodFinder.find. Also allows to test for state other than the return value of the method.

%w[a b c].find_method { |a| a.unknown(1) ; a == %w[a c] }
#=> ["Array#delete_at", "Array#slice!"]
10.find_method { |n| n.unknown(3) == 1 }
#=> ["Fixnum#%", "Fixnum#<=>", "Fixnum#>>", "Fixnum#[]", "Integer#gcd", "Fixnum#modulo", "Numeric#remainder"]

Inside find_method‘s block, the receiver is available as block argument and the special method unknown is used as a placeholder for the desired method.

find_method can be called without passing a block. This is the same as calling MethodFinder.find.

10.find_method(1,3)
#=> ["Fixnum#%", "Fixnum#<=>", "Fixnum#>>", "Fixnum#[]", "Integer#gcd", "Fixnum#modulo", "Numeric#remainder"]


23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/methodfinder.rb', line 23

def find_method(*args, &block)
  if block
    mets = MethodFinder.methods_to_try(self).select do |met|
      self.class.class_eval("alias :unknown #{met}")
      obj = self.dup rescue self # dup doesn't work for immutable types
      block.call(obj) rescue nil
    end
    mets.map { |m| "#{self.method(m).owner}##{m}" }
  else
    MethodFinder.find(self, *args)
  end
end