Object#methods_returning - to work out which method on an object returns what we want
require 'stringio' | |
require 'timeout' | |
class Object | |
def methods_returning(expected, *args, &blk) | |
old_stdout = $> | |
$> = StringIO.new | |
methods.select do |meth| | |
Timeout::timeout(1) { dup.public_send(meth, *args, &blk) == expected rescue false } rescue false | |
end | |
ensure | |
$> = old_stdout | |
end | |
end | |
# ---------------- | |
p [1, nil, 'x'].methods_returning [1, 'x'] | |
# => [:compact, :compact!] | |
p [1, 2, 3].methods_returning [3, 2, 1] | |
# => [:reverse, :reverse!] | |
p [1, 2, 3].methods_returning [] | |
# => [:values_at, :clear, :singleton_methods, :protected_methods, :instance_variables] | |
p [1, 2, 3].methods_returning([2, 4, 6]) { |i| i * 2 } | |
# => [:collect, :collect!, :map, :map!, :flat_map, :collect_concat] | |
p [1, 2, 3].methods_returning('123') | |
# => [:join] | |
p (1..5).methods_returning([[1, 3, 5], [2, 4]], &:odd?) | |
# => [:partition] | |
p 'A'.methods_returning 'a' | |
# => [:downcase, :swapcase, :downcase!, :swapcase!] |
This comment has been minimized.
This comment has been minimized.
This might be a good addition to Pry. Here's something I always forget: irb [1.9.3]$ 10.methods_returning [3,1], 3
=> [] But the |
This comment has been minimized.
This comment has been minimized.
https://github.com/citizen428/methodfinder is similar, written starting about 3 years ago. |
This comment has been minimized.
This comment has been minimized.
How long until someone manages to wipe out their filesystem by using this on the wrong object? :-P |
This comment has been minimized.
This comment has been minimized.
@kotp |
This comment has been minimized.
This comment has been minimized.
+1 |
This comment has been minimized.
This comment has been minimized.
I thought I'd seen this idea somewhere before, kotp - good find! |
This comment has been minimized.
This comment has been minimized.
there is a similar thing in Smalltalk |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
This is a novel idea for finding library methods if you're unfamiliar with its methods - helps you narrow your focus before you dive into the doc/code. I think I'll try this next time I use a new gem, though I suspect it could still be useful for stdlib type stuff. Nice one!