Ruby: Turtles all the way down

Posted by science on July 29, 2007

Turtles all the way down

Consider the following Ruby:

if [1,2].include?(contact_id)

instead of

if (contact_id == 1) || (contact_id == 2)

This is a great example of object oriented turtles all the way down in Ruby - the interpreter makes it very easy to create an array and call one of its methods against a variable, making re-use of an array method for boolean evaluation.

In C and many other languages, compactness is usually associated with performance, but not in Ruby: compactness is mostly associated with readability. I suppose this is partly cultural - Ruby is slow, so Ruby programmers often strive to make their code “elegant” where elegance refers to a readability and intuitive structure not found in many languages.

I actually use this structure for more practical things too. For example, when I’m writing unit tests, I often have to iterate over a method several times with different starting states. I often pass those starting states in as an array of hashes, with hash values holding the starting state variables for each loop.

[{:property => Property.new, :contact => Contact.new}],
  {:property => Property.find(10), :contact => Contact.new},
  {:property => Property.find(10), :contact => Contact.find(2)}].each do |context|
    assert method_to_test(context[:contact], context[:property])
end

Of course you can do something similar in any language, but often that would involve creating a new method that you call or whatever. Ruby just makes it easy to instantiate complex structures on the fly. Of course, you have to be careful.

Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

Comments