Skip to content

Instantly share code, notes, and snippets.

@peterc
Last active October 29, 2023 03:10
Show Gist options
  • Star 75 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save peterc/8607915 to your computer and use it in GitHub Desktop.
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
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!]
@hemanth
Copy link

hemanth commented Jan 31, 2014

@kotp 👍

@fahim-patel
Copy link

+1

@peterc
Copy link
Author

peterc commented Jan 31, 2014

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

@alaa-alawi
Copy link

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