Ruby Beauty – Dynamically Invoking Methods

April 7, 2010 • Damien White

Continuing with my exploration of Ruby as a .NET guy, here’s another example of Ruby’s expressive syntax in action. I decided to add bite size snippets of some of the cool things I encountered in Ruby and Rails. If you are interested in others, see my other Ruby posts.

Within the context of Ruby, you can call a method in one of two ways. The first, and most frequently used, is the standard “dot” notation. Take the following class:

class SampleClass
    def say_hello(name)
        puts "Hello #{name}"
    end
end

To then call that method:

obj = SampleClass.new
obj.say_hello('Damien')

This works fine for things you know about, but what if you wanted to call a method dynamically at runtime?

Using the same SampleClass example, we can also do the following:

obj = SampleClass.new
obj.send(:say_hello, 'Damien')

By using Ruby’s send method, we can pass the name of the method as a symbol and an array of arguments. So in this example, we want to call the say_hello method, passing the argument of “Damien.”  You could also use a string in the place of the symbol used in the last example:

obj = SampleClass.new
obj.send('say_hello', 'Damien')

This is most often used in metaprogramming. Continuing with my exploration of Ruby (and Rails), I got sucked into metaprogramming thanks to Metaprogramming Ruby (Facets of Ruby) from The Pragmatic Bookshelf. All it took was the sample chapter and I was hooked. I started reading the Kindle version of the book and so far it’s fantastic.

Of course, you can do this in .NET as well, but Reflection just isn’t really pretty. Although C# 4.0’s dynamic feature is a thing of beauty. Hooray for the DLR.

Posted in ruby and tagged with Ruby

Damien White

I am a software architect with over 16 years of experience. I simply love coding! I have a driving passion for computers and software development, and a thirst for knowledge that just cannot be quenched. I'm happy to share what I know in my quest to learn as much as possible. I focus most of my time on web development using Ruby on Rails, Ember.js, and ASP.NET MVC.

comments powered by Disqus