Snippet / January 16, 2009

The difference between eval, class_eval, module_eval, and instance_eval

By Daniel Lv/1231 Views/0 Comments

At first glance, one would think that there is no difference between module_eval and class_eval, in fact, the method class_eval is an alias for module_eval.

Let's take a look at the whole eval family:

  • module_eval
  • instance_eval
  • eval

module_eval
module_eval allows you to define new instance method for a class.

String.module_eval do
  def foo
    "bar"
  end
end

"string".foo    #=> "bar"

instance_eval
instance_eval evaluates a string or the given block within the context of the receiver. Be careful when using this method as it could create a public class method or public instance method.

String.instance_eval do
  def foo
    "bar"
  end
end

String.foo     #=> "bar"

foo = "foo"
foo.instance_eval do
  def bar
    "bar"
  end
end
foo.bar        #=> "bar"

eval
eval only takes a string to evaluate, unlike module_eval or instance_eval which can both evaluate a block instead. eval will evaluate the string in the current context or if a binding is given.

def getBinding(str)
  return binding
end
str = "hello"
eval "str + ' Fred'"                       #=> "hello Fred"
eval "str + ' Fred'", getBinding("bye")    #=> "bye Fred"

My Conclusion
module_eval is almost always what you want to use, and eval should always be your last resort.

Comments

Interesting post?  Show some love and post a comment!
Using pieces of this code?  Post a link!

Add a Comment