Showing posts with label Instance_eval. Show all posts
Showing posts with label Instance_eval. Show all posts

Tuesday, January 08, 2008

obj.instance_eval and mod.module_eval(mod.class_eval) usage


class C
def initialize
@x = 1
end
end

c = C.new
c.instance_eval { puts @x }
puts c.instance_variable_get "@x"

C.class_eval do
def some_method
puts "Created in class_eval"
end
end
c = C.new
c.some_method

Monday, July 09, 2007

Ruby instance_eval example


class Klass
def initialize
@secret = 99
end
end
k = Klass.new
p k
p k.instance_eval('self')
k.instance_eval(%q)
p k.instance_eval { self }
puts k.instance_eval { @secret }
puts k.name
p k.methods(false)

k.instance_eval do
def first_name
'yu'
end
end

puts k.first_name

# Evaluates a string containing Ruby source code, or the given block, within the con-
# text of the receiver (obj). To set the context, the variable self is set to obj while the
# code is executing, giving the code access to obj’s instance variables.

k.instance_variable_set(:@secret, 100)
puts k.instance_variable_get(:@secret)

p k.instance_variables

# >> #
# >> #
# >> #
# >> 99
# >> test
# >> ["name"]
# >> yu
# >> 100
# >> ["@secret"]