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:
To then call that method:
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:
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:
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.