Monday, November 17, 2008

Writing Prettier Ruby Code with instance_eval

instance_eval is a method of ruby Object class that lets you pass a string of ruby code or a block to be evaluation in the scope of that object.

Through instance_eval you can actually add new methods to a particular object. This can help you write more pretty and readable code. for example, we can define a new average method for an array of numbers

>> a = [1, 2, 3, 4, 5, 6, 7, 8]
=> [1, 2, 3, 4, 5, 6, 7, 8]
>> a.sum
=> 36
>> a.size
=> 8
>> a.average
NoMethodError: undefined method `average' for [1, 2, 3, 4, 5, 6, 7, 8]:Array
    from (irb):14
>> a.sum / a.size
=> 4
>>

With instance_eval we can add that new method here


a.instance_eval do
    def average ; sum/size end
end
>> a.average
=> 4

In a lot of cases this approach can be useful.

3 comments:

AhmedElGamil said...

This is really cool :)
and you are so right about the usage, it is very handy

Thanks for the tip :)

mahmoud said...

You are welcome Ahmed,

actually i used this method in a piece of code that would have looked very messy without it..

i'll probably be talking about it soon isA

Anonymous said...

This seems to be not so messy at all:

a = [1, 2, 3, 4, 5, 6, 7, 8]
a.size
a.sum rescue puts("Method not found")
a.average rescue puts("Method not found")

def a.sum
inject(0){|a,e| a + e}
end

def a.average
sum / size
end

a.average