Reputation: 1425
I have an array of methods like this:
def method1
1
end
def method2
2
end
m = [method1, method2]
I want to print the method names and values that are in m
so that I get an output like:
method1: 1
method2: 2
Is it possible to get the name of a defined method as string or symbol? How can I get a method name as string or symbol?
Upvotes: 0
Views: 1314
Reputation: 107097
After this the line m = [ method1, method2 ]
the variable m
has no information anymore about the methods that were called to assign [1, 2]
to m
.
Therefore, instead of storing the values that were returned by the methods I purpose to just store the method names in the array and use public_send
to call the method when you need both their names and their return values:
m = [:method1, :method2]
def method1
1
end
def method2
2
end
m.each { |name| puts "#{name}: #{public_send(name)}" }
# => method1: 1
# method2: 2
Or you might want to use a hash to store the method names and the returned values right away when assigning tehm to m
:
m = { method1: method1, method2: method2 }
m.each { |name, value| puts "#{name}, #{value}" }
Upvotes: 4