Reputation: 89
I'm fairly new to Ruby and rails so I'm not quite sure how to do things "the right way" but I have several methods from Rspec (get, post, put, delete) that I would like to pass into an array so I can loop over them to execute the same code each time. I thought that'd be fairly easy but I can't figure out how to do it.
Does anyone know if that's possible, good practice, and how to do it?
Upvotes: 1
Views: 1646
Reputation: 898
class Message
def method1
#something
end
def method2
#something
end
end
message = Message.new
methods = [ 'method1', 'method2' ]
methods.each{ |method| message.send(method) }
or you can use symbols instead string when you declare your methods because is more idiomatic
It's also best practice to use public_send instead of send, unless you're actually trying to call private methods.
Upvotes: 0
Reputation: 5563
['get', 'post', 'put', 'delete'].each {|m| obj.send(m) }
I see things done this way frequently in Ruby projects.
Upvotes: 4