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:
Expand|Select|Wrap|Line Numbers
- 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
Expand|Select|Wrap|Line Numbers
- This method was made by calling instance_eval
- Current 'self': #<Foo:0x8f098>
- Current class of 'self': Foo
Expand|Select|Wrap|Line Numbers
- 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
Expand|Select|Wrap|Line Numbers
- 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!