Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

The Power of IronRuby

As a finale to the IronRuby introduction, I want to leave you wanting more. Instead of just writing a simple Hello World application, I want you to see how great IronRuby is and how it can enhance your development work.

Ruby comes with very powerful built-in metaprogramming capabilities. One of its features is a built-in method called method_missing (read more about it in Chapter 6, "Ruby's Code-Containing Structures"). The method_missing method catches all calls to undefined methods and lets you handle them the way you want.

In Listing 4.1, by using method_missing, I implement a Recorder class that records calls to methods and plays them back on request. Notice how easy it is to accomplish this with Ruby. Even though you might not be familiar with all the syntax elements, this code is pretty simple and straightforward.

Listing 4.1. A Recorder Class Implementation

class Recorder
  def initialize
    @calls = []
  def method_missing(method, *args, &block)
    @calls << [method, args, block]
  def playback(obj)
    @calls.each do |method, args, block|
      obj.send method, *args, &block

Now that the Recorder class is ready, we can take advantage of it. Unlike regular Ruby code, we can take advantage of IronRuby capabilities and run the Recorder class with .NET code. Listing 4.2 takes advantage of the Stack class of the .NET Framework and runs recorded operations on it using our Recorder class.

Listing 4.2. Using the Recorder Class on a CLR Object

recorder = Recorder.new
recorder.push 5.6
recorder.push 1
recorder.push "IronRuby"

# Run the recorded calls on the CLR Stack instance
stack = System::Collections::Stack.new

stack.each { |x| puts x }
# Prints "IronRuby
#         1
#         IronRuby
#         1"
  • + Share This
  • 🔖 Save To Your Account