Reputation: 1
Is it possible to call all parameterless methods for a given class object by using reflection in Ruby?
Upvotes: 0
Views: 404
Reputation: 110665
def call_paramater_less_methods(instance)
instance.class.instance_methods(false).each do |m|
instance.public_send(m) if instance.method(m).arity.zero?
end
end
class C
def a() puts "a says hi" end
def b() puts "b says ho" end
def c(s) puts "c says #{s}" end
end
call_paramater_less_methods(C.new)
# b says ho
# a says hi
Optionally,
instance.public_send(m) if instance.method(m).arity.zero?
can be replaced with
instance.method(m).call if instance.method(m).arity.zero?
Upvotes: 2