zzz6519003 / blog

My blog about coding
4 stars 1 forks source link

instance_eval() #27

Open zzz6519003 opened 10 years ago

zzz6519003 commented 10 years ago

Here's from the doc

instance_eval(...) public Evaluates a string containing Ruby source code, or the given block, within the context of the receiver (obj). In order to set the context, the variable self is set to obj while the code is executing, giving the code access to obj’s instance variables. In the version of instance_eval that takes a String, the optional second and third parameters supply a filename and starting line number that are used when reporting compilation errors.

class Klass
  def initialize
    @secret = 99
  end
end
k = Klass.new
k.instance_eval { @secret }   #=> 99
class MyClass
  def initialize
    @v = 1
  end
end
obj = MyClass.new
obj.instance_eval do
  self        # => #<MyClass:0x3340dc @v=1>
  @v          # => 1
end

v = 2
obj.instance_eval { @v = v }
obj.instance_eval { @v }      # => 2

Ruby 1.9 introduced a method named instance_exec(). This is similar to instance_eval(), but it also allows you to pass arguments to the block:

class CleanRoom
  def complex_calculation
    # ...
    11
  end

  def do_something
    # ...
  end
end

clean_room = CleanRoom.new
clean_room.instance_eval do
  if complex_calculation > 10
    do_something
  end
end

So send executes a method whereas instance_eval executes an arbitrary block of code (as a string or block) with self set to the object that you're calling instance_eval on. *****