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"]

No comments :