Skip to content

Instantly share code, notes, and snippets.

@kmicinski
Created June 6, 2015 05:48
Show Gist options
  • Save kmicinski/2aff33814537267e9cc2 to your computer and use it in GitHub Desktop.
Save kmicinski/2aff33814537267e9cc2 to your computer and use it in GitHub Desktop.
Ruby Method example
# Get the set of method symbols that end in ?
predicatesSymbols = 1.methods.select { |x| if x.to_s =~ /.*\?/ then true end }
# For each symbol, get the `Method` object corresponding to that symbol
methods = predicatesSymbols.map { |symbol| 1.method(symbol) }
# Filter out methods that don't accept one argument
resultingValues = methods.map do |meth|
begin
# Create an array of arguments to call the method with, using
# `arity` to look up how many parameters it expects.
a = Array.new(meth.arity,1)
# Return the method's name and the result of calling it with
# `arity` ones
[meth.name,meth.call(*a)]
rescue
# This could crash because there could be a type error, in that
# case just return `nil` and we'll filter it out in the next step
nil
end
end
# Filter out errors
resultingValues.select! { |x| x }
# Print out each predicate and its corresponding result after calling
resultingValues.each { |x| puts "Method #{x[0]} returned #{x[1]}" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment