1

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?

2 Answers 2

4
['get', 'post', 'put', 'delete'].each {|m| obj.send(m) }

I see things done this way frequently in Ruby projects.

Sign up to request clarification or add additional context in comments.

3 Comments

My only suggestion would be to use %w(get post put delete).each...
ok, I was doing m.send and not obj.send(m). I'm gonna look into this. Thank you :)
My pleasure, hope it helps
0
  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.

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.