Last active
October 29, 2023 03:10
-
-
Save peterc/8607915 to your computer and use it in GitHub Desktop.
Object#methods_returning - to work out which method on an object returns what we want
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 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 dup
+ rescue false
is not helping me remember... 😄
https://github.com/citizen428/methodfinder is similar, written starting about 3 years ago.
How long until someone manages to wipe out their filesystem by using this on the wrong object? :-P
@kotp 👍
+1
I thought I'd seen this idea somewhere before, kotp - good find!
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 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!