A Ruby Idiom: Defining Methods Based on Conditions at Runtime

General 5 October 2009 | 0 Comments

On pages 36 and 37 of The Ruby Way (2nd Edition) Hal talks about “Coding at Runtime.” He specifically mentions how while ifdef directives can be used in C to change how things are defined depending on conditions set prior to the compile, you can just do the same at runtime in Ruby.

For example, let’s say your app is designed to run on multiple platforms, but a certain action has to be executed in a totally different way for a couple of platforms (a common situation where Windows is involved). You could define your logic like this:

if platform == Windows
  action1
elsif platform == Linux
  action2
else
  default_action
end

To this sort of arrangement Hal says: “Of course, there is a small runtime penalty for coding in this way since the flag may be tested many times in the course of execution.” He then presents a technique where a method itself is defined at run-time based upon the condition:

if platform == Windows
  def my_action
    action 1
  end
elsif platform == Linux
  def my_action
    action2
  end
else
  def my_action
    default_action
  end
end

To this, Hal says: “In this way, the same result is achieved, but the flag is only evaluated once; when the user’s code calls my_action, it will already have been defined appropriately.”

Personally I’m not entirely convinced by Hal’s specific example in The Ruby Way, but it’s a handy reminder of how dynamic Ruby is. I’m sure there are some great examples of this technique in the wild.

Leave a Reply