- Overview
- Installing IronRuby
- Executables and Tools
- Development Environments
- The Power of IronRuby
- Summary
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 = [] end def method_missing(method, *args, &block) @calls << [method, args, block] end def playback(obj) @calls.each do |method, args, block| obj.send method, *args, &block end end end
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.pop recorder.push 1 recorder.push "IronRuby" # Run the recorded calls on the CLR Stack instance stack = System::Collections::Stack.new recorder.playback(stack) recorder.playback(stack) stack.each { |x| puts x } # Prints "IronRuby # 1 # IronRuby # 1"