Auto-redefining methods

October 11th, 2004 § 3 comments

While I was playing with Ruby, reading its documentation and the free excerpts of Programming Ruby, I came across a really interesting example of the language’s power:

class Test
  def doSomething
    def doSomething
    @calculatedValue = self.runLongCalculation

This technique, very useful in a many contexts, allows a method to redefine itself. In the example above, when the method is called for the first time, it changes its own definition to return the value of a instance variable and assigns a value to that variable. The next invocations of the method will, of course, use its redefined version.

The book shows a more interesting and sophisticated example, but even the example above can show how Ruby allows a programmer to express exactly what he wants in a clear way.

§ 3 Responses to Auto-redefining methods"

  • Jonas Galvez says:

    *cough* Python version *cough*:

    class Test:
        def doSomething(self):
            def doSomething():
                return self.calculatedValue
            self.calculatedValue = self.runLongCalculation()
            self.doSomething = doSomething
            return self.calculatedValue

  • Ronaldo says:

    I knew it wouldn’t be long until you came with a Python counter-example. :-)

    What I found interesting in the more sophisticated example provided by the book is that it defined a dynamic method that received another method as a parameter and converted it in a new method that behaved as described above. Considering Ruby’s clarity, it was a truly esoteric example. The resulting syntatic surgar was the best thing about it.

    From what I’ve seen in my studies (and as you said in your blog), Ruby and Python are alike in many areas. But the differences are also big in other areas because Ruby is much more OO than Python and because its syntax is designed to be much more extensible than Python’s.

    At the end of the day, however, each new language is worthy learning. Each servers a different purpose, and it’s interesting by itself — except, maybe, for PHP. 😛

  • Sei says:

    Ruby code is so much easier to read

What's this?

You are currently reading Auto-redefining methods at Reflective Surface.