0

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

1 Answer 1

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

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?
Sign up to request clarification or add additional context in comments.

2 Comments

And then call them with send or public_send or get the method objects and use call (m = obj.method(name); m.call). The "class object" terminology makes me think they're talking about class methods but the procedure is pretty much the same.
@muistooshort, I see I did not answer the question that was asked. Thanks for letting me know. I've done an edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.