Created
June 6, 2015 05:48
-
-
Save kmicinski/2aff33814537267e9cc2 to your computer and use it in GitHub Desktop.
Ruby Method example
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
# 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