Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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!]
@seanhandley

This comment has been minimized.

Copy link

commented Jan 25, 2014

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!

@sshaw

This comment has been minimized.

Copy link

commented Jan 30, 2014

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... 😄

@kotp

This comment has been minimized.

Copy link

commented Jan 31, 2014

https://github.com/citizen428/methodfinder is similar, written starting about 3 years ago.

@vidarh

This comment has been minimized.

Copy link

commented Jan 31, 2014

How long until someone manages to wipe out their filesystem by using this on the wrong object? :-P

@hemanth

This comment has been minimized.

Copy link

commented Jan 31, 2014

@kotp 👍

@fahim-patel

This comment has been minimized.

Copy link

commented Jan 31, 2014

+1

@peterc

This comment has been minimized.

Copy link
Owner Author

commented Jan 31, 2014

I thought I'd seen this idea somewhere before, kotp - good find!

@alaa-alawi

This comment has been minimized.

Copy link

commented Feb 7, 2014

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
You can’t perform that action at this time.