Monthly Archives: December 2007

Ruby magic

Richard Moore blogged about setters/getters vs direct access to member variables and why encapsulation is good today. Ruby excels in this aspect, IMHO:

With Ruby your code is the same regardless you are accessing a variable or a method. This means something that now is a variable, you can transform it in the future in a method with calculates a value and the code accessing it does not change at all.
Imagine you have a method to print the volume of a bottle and you had stored the volumes in pints (Imperial units). Your code is:

volume = get_bottle_volume_from_database() # these are pints, you would be getting the "10" value from a database

puts "The volume is " + volume.to_s
=> The volume is 10

Now you want to move to international units (litres). You can do this:


def volume
return get_bottle_volume_from_database() * 0.473176475 # Transform from pints to litres
end

puts "The volume is " + volume.to_s # See? "volume" is a method here (it was a variable in the former example) but our code has not changed!

Of course this is a contrived example but keep in mind this syntax allows for all kinds of magic. For example, it makes Ruby on Rails feasible