是否可以通过在Ruby中使用反射来调用给定类对象的所有无参数方法?
答案 0 :(得分:2)
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
任选地,
instance.public_send(m) if instance.method(m).arity.zero?
可以替换为
instance.method(m).call if instance.method(m).arity.zero?