This is a read-only archive!

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
June 19, 2007 @ 12:52 AM PDT
Cateogory: Programming
Tags: Ruby

4 Comments

Rupert
Quoth Rupert on June 25, 2007 @ 10:36 AM PDT

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

Brian
Quoth Brian on June 27, 2007 @ 6:59 AM PDT

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.

SEOTAIJI
Quoth SEOTAIJI on May 22, 2008 @ 2:13 AM PDT

I've been trying to figure out the difference between class_eval and instance_eval. Thanks for your post!

Tim
Quoth Tim on May 28, 2009 @ 7:53 AM PDT

Nicely done! Thanks :-) It really cleared things up for me.