Thursday, February 15, 2007

Ruby Evaluation options article on InfoQ

Yesterday, I published a fairly long article on InfoQ about Evaluation Options in Ruby. The article covers eval, instance_eval, class_eval and provides examples of using each of them.

Feedback welcome.


  1. That was a very interesting read. Thanks for the link.

    Umm... could you please (re)explain why your second form of attr_init was better optimized than the first form?

    I couldn't understand this: "It was not obvious at first to me, but the following solution is far superior since it only requires one call to eval instead of a new eval with each call to the defined method." To me it seems both forms result in the same number of eval calls. What am I not seeing?

  2. Aman

    I created an example, but it's a bit long and looks much better on pastie.

    If you copy that example and execute it, you'll notice that the call to attr_init_optimized causes an eval to occur; however, all the calls to baz do not require an eval. Conversely, the call to attr_init does not require an eval, but each call to bar causes an eval to occur.

  3. Thanks, Jay! The example helped.

    Basically, in the unoptimized case, the eval statement became part of the method you were defining and hence got executed each time the defined method was called; whereas in the optimized case, the eval statement was not part of the defined method itself (as it wasn't within it): the contents of the method were fixed when the method itself was defined using eval. :-) I should have caught that.


Note: Only a member of this blog may post a comment.