class_eval vs. instance_eval in Classes
For my own sake, I want to write this down while I still remember it.
class_eval executes a block in the context of a Class. instance_eval executes a block in the context of an instance. When you do def inside a class_eval, you always define a new instance method. (Unless you do def self.something in which case you define a Class method, same as always.)
When you do def inside an instance_eval, it depends on what exactly your receiver is. If you do a def inside an obj.instance_eval, you define a singleton method for obj, which affects no other objects of the same class. If you do a def inside a SomeClass.instance_eval, you define a class method for that Class.
So these all seem to do the same thing, and allow you to do Foo.foo<.
# ONE
class Foo
end
def Foo.foo
puts "FOO"
end
# TWO
class Foo
def self.foo
puts "FOO"
end
end
# THREE
class Foo
end
class << Foo
def foo # corrected, thanks Rupert
puts "FOO"
end
end
# FOUR
class Foo
class << self
def foo
puts "FOO"
end
end
end
# FIVE
class Foo
end
Foo.class_eval do
def self.foo
puts "FOO"
end
end
# SIX
class Foo
end
Foo.instance_eval do
def foo
puts "FOO"
end
end

4 Comments
Thanks Brian
....just trying to get my head round all this stuff, so very helpful - muchly grateful.
I did find one wee errorette in your examples though. The 3rd example shouldn't have a self in it, so it should be:
class Foo end class << Foo def foo puts "FOO" end end[ah-ha it's the << it didn't like - sorry for the mess - I'll stop if it doesn't work this time!]
not that I know through any expertise in these things - I'm going through the 'learning by trial and error process'!
Thanks again - Cheers
Rupert
Right you are. Thanks for letting me know. Glad someone else read it.
Wordpress is really horrible about parsing comments and posts. Sometimes it preserves HTML characters, sometimes it escapes them. Blarg. It bites me all the time too.
I've been trying to figure out the difference between class_eval and instance_eval. Thanks for your post!
Nicely done! Thanks :-) It really cleared things up for me.
Speak your Mind
Preview