Skip to content

Instantly share code, notes, and snippets.

@domgetter
Last active August 3, 2016 20:19
Show Gist options
  • Save domgetter/79ce104c162008ca1f15 to your computer and use it in GitHub Desktop.
Save domgetter/79ce104c162008ca1f15 to your computer and use it in GitHub Desktop.
Will tell you what Ruby method(s) you want given the input and output Now works with arguments!
class HaveWant
attr_reader :answers
def initialize(*have, want)
@have = have[0]
@args = have[1..-1]
@want = want
find_matches
end
private
def find_matches
@answers = @have.methods.map do |method|
@have.dup.method(method)
end.select do |method|
begin
method.call(*@args).eql? @want
rescue
false
end
end.map(&:name)
end
end
havewant = HaveWant.new("hello", "HELLO")
puts havewant.answers
# upcase
# swapcase
# upcase!
# swapcase!
havewant = HaveWant.new([3,3,3,4,5], 5)
puts havewant.answers
# last
# pop
# length
# size
# count
# max
# and sometimes
# sample
# you can also pass arguments between what you have and what you want
#
havewant = HaveWant.new([3,3,3,4,5], 2..3, [3,4])
puts havewant.answers
# []
# values_at
# slice
# slice!
puts HaveWant.new("foo", "bar", "foobar").answers
# +
# concat
# <<
@hauleth
Copy link

hauleth commented Jul 31, 2016

You can use def initialize(have, *args, want) instead: http://ideone.com/V0pVF0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment