0

Lets say I have two methods:

def hello
 'hello'
end

def world
 'world'
end

Now I want to call these methods in a fashion like this:

try_retry{
  hello
}
try_retry{
  world
}

assume try_retry is a method that will retry the block of code if an error happens. There are a lot of these methods so is it possible to iterate over the blocks? Something like:

array_of_methods = [hello,world]
array_of_methods.each do |method|
  try_retry{
    method
  }
end

the problem is the methods get evaluated on this line:

array_of_methods = [hello,world]

3 Answers 3

1

You can do

array_of_methods = [method(:hello), method(:world)]

And you can call them like

array_of_methods.each { |m| m.call }
Sign up to request clarification or add additional context in comments.

1 Comment

Note: with this answer method(:hello) is an object for the method hello and does not directly call the method. This is very nice because you have more options as to what to do with the method, but if you are only calling the method, using send is more efficient.
0

Let's say that you have the methods hello and world. If you want to call these methods while iterating over them, you can do it as such

['hello', 'world'].each do |m|
  send(m)
end

1 Comment

Method names are usually symbols. Besides, you have to call send within try_retry { ... } to actually solve the OPs problem.
0

Depending on the origin of this array of method names you might not want to allow private or protected methods to get called so public_send will allow for only public methods to be called.

array_of_methods = ['hello', 'world']

array_of_methods.each {|m| public_send(m)}

Comments

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.