I'm using Ruby 1.8.6 btw.
For the longest time today (it seems) I've been trying to understand exactly the operating difference between class_eval and instance_eval. There are some obvious differences I'm perfectly aware of (e.g. class_eval is only on Class objects), but the reality is that some irb tinkering has left me more confused than ever. Given the following:
Gives me this:
If I then try doing the exact same thing with class_eval instead:
I then get the same damn result:
So, what's the difference between these two calls? In this particular situation? In general?
Some clear thoughts would be ever so appreciated!
For the longest time today (it seems) I've been trying to understand exactly the operating difference between class_eval and instance_eval. There are some obvious differences I'm perfectly aware of (e.g. class_eval is only on Class objects), but the reality is that some irb tinkering has left me more confused than ever. Given the following:
Code:
class Foo
# could be any class
end
f = Foo.new
# Try out instance eval on f's class (Foo)
f.class.instance_eval do
define_method :made_by_inst_eval do
puts "This method was made by calling instance_eval"
puts "Current 'self': #{self}"
puts "Current class of 'self': #{self.class}"
end
end
f.made_by_inst_eval
Code:
This method was made by calling instance_eval Current 'self': #<Foo:0x8f098> Current class of 'self': Foo
Code:
f.class.class_eval do
define_method :made_with_class_eval do
puts "This method was made by calling class_eval"
puts "Current 'self': #{self}"
puts "Current class of 'self': #{self.class}"
end
end
f.made_with_class_eval
Code:
This method was made by calling class_eval Current 'self': #<Foo:0x8ec88> Current class of 'self': Foo
Some clear thoughts would be ever so appreciated!
Comment