method finder for Ruby

October 04, 2008

Here's something fun:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def find_method(target, *args)
  raise "must pass in at least the expected result" unless args.size > 0
  expected = args.pop

  to_call = if args.empty?
              lambda {|t, m| t.send(m) }
            else
              lambda {|t, m| t.send(m, *args) }
            end
  target.methods.select do |m|
    next if %w(id type gem).include?(m)
    t = target.is_a?(Numeric) ? target : target.clone
    to_call[t, m] == expected rescue nil
  end
end

p find_method("asdf", "ASDF")
p find_method([1,2,3], [1,2], [1,2])
p find_method(2,2,4)

This will print out:

["swapcase", "swapcase!", "upcase", "upcase!"]
["&", "replace"]
["*", "+", "**"]
blog comments powered by Disqus