Method: MethodFinder.find

Defined in:
lib/methodfinder.rb

.find(obj, res, *args, &block) ⇒ Object

Provided with a receiver, the desired result and possibly some arguments, MethodFinder.find will list all methods that produce the given result when called on the receiver with the provided arguments.

MethodFinder.find(10, 1, 3)
#=> ["Fixnum#%", "Fixnum#<=>", "Fixnum#>>", "Fixnum#[]", "Integer#gcd", "Fixnum#modulo", "Numeric#remainder"]
MethodFinder.find("abc","ABC")
#=> ["String#swapcase", "String#swapcase!", "String#upcase", "String#upcase!"]
MethodFinder.find(10, 100, 2)
#=> ["Fixnum#**"]
MethodFinder.find(['a','b','c'], ['A','B','C']) { |x| x.upcase }
#=> ["Array#collect", "Array#collect!", "Enumerable#collect_concat", "Enumerable#flat_map", "Array#map", "Array#map!"]


70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/methodfinder.rb', line 70

def find(obj, res, *args, &block)
  redirect_streams

  mets = methods_to_try(obj).select do |met|
    o = obj.dup rescue obj
    m = o.method(met)
    if m.arity <= args.size
      a = args.empty? && ARGS.has_key?(met) ? ARGS[met] : args
      m.call(*a, &block) == res rescue nil
    end
  end
  mets.map { |m| "#{obj.method(m).owner}##{m}" }
ensure
  restore_streams
end