Get the Powers to Act from Fresh Ideas



December 21, 2012

Meta-programming in Ruby : Part 16 : instance_eval

There are altogether 16 posts on this topic of meta-programming in Ruby language. Our approach encourages hands-on experimentation. The exercises here are specially designed to facilitate self-study and other independent modes of learning.

Provided we can find time amidst our busy schedule(well, who is not busy these days?), we will also discuss meta-programming in other languages such as Lisp and python.

Code 1

instance_eval and self.


# instance_eval evaluates a block of code
# with self set to the object that's receiving the instance_eval call.

add_two = Proc.new { self + 2 }

puts 1.instance_eval(&add_two) #=> 3
puts 2.instance_eval(&add_two) #=> 4

"stellar coding staff".instance_eval{p self}
[1970, 1980, 1990, 2000].instance_eval{p self}
{'a'=> 1970, 'water'=> 1990, 'gold'=>2010}.instance_eval{p self}
puts "\n\n"


# Here's a second example using an implicit method receiver.
call_reverse = Proc.new { self.reverse }

p "alan akhoe kid".instance_eval(&call_reverse)
p ["x", "y", "z"].instance_eval(&call_reverse) #=> ["z", "y", "x"]
p [1, 34, 117, 997].instance_eval(&call_reverse)
# OK BAD # p 12121.instance_eval(&call_reverse)


Result 1



[root@localhost ruby_tutor]# ruby ie_self.rb
3
4
"stellar coding staff"
[1970, 1980, 1990, 2000]
{"a"=>1970, "water"=>1990, "gold"=>2010}


"dik eohka nala"
["z", "y", "x"]
[997, 117, 34, 1]


Code 2

We can display private attributes using instance_eval.


class C
def initialize
@a = 0
end
def next
@a += 1
end
end
w = C.new
p w.next
p w.next; puts;puts

p w.instance_eval "@a" #=> 2
p w.instance_eval { @a } #=> 2
p C.new.instance_eval { @a } #=> 0


Result 2



[root@localhost ruby_tutor]# ruby ie_and_private_vars.rb
1
2


2
2
0


2 comments:

  1. Here is a site you should study.

    BackYard Chickens is powered by Huddler Families

    http://www.huddler.com/

    BackYard Chickens ; Most likey in PHP.

    ReplyDelete
    Replies
    1. Thank you very much.I've seen it. I learn alot from their business.

      Delete