uqiul06
uqiul06

Reputation: 1

Ruby - Calling all methods without arguments for a class object

Is it possible to call all parameterless methods for a given class object by using reflection in Ruby?

Upvotes: 0

Views: 404

Answers (1)

Cary Swoveland
Cary Swoveland

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

Related Questions