Skip to content

Calling dynamic methods in Ruby on Rails

Posted on 11 September 2007

To utilise dynamic method names in Ruby on Rails you can use Ruby's send method to pass a message to an object.

For example:

["foo", "bar"].each do |method|
	MyClass.send(method)
end

The above is obviously a very crude example but it's the same as calling MyClass.foo and MyClass.bar.

The point is that the array could be dynamic and this means you can write code that calls methods prior to knowing what those methods may well be.

You can use send to call dynamic helper methods by just calling it on it's own.

View the snippets archive ››

2 comments made

Bob commented on 14 Sep 07 at 11:17

Awesome! Thanks much!

Josh commented on 18 Jul 08 at 08:03

Thanks for the find. You should also mention that respond_to? can verify the presence of a dynamic method. (:

Got something to say?

About

Paul is a web developer for Kyanmedia web agency. He's lucky enough to write in Ruby on Rails full-time and uses this site to post snippets of code.

Contact

my name at gmail.com

More snippets

Take a look in the archive

Need a website?

Contact my employer. Make sure to check out our portfolio of work.

Hosting

I recommend hostingrails.com