The instance_eval (opens new window) method is available on all objects. It evaluates code in the context of the receiver:
instance_eval
object = Object.new object.instance_eval do @variable = :value end object.instance_variable_get :@variable # => :value
instance_eval sets self to object for the duration of the code block:
self
object
object.instance_eval { self == object } # => true
The receiver is also passed to the block as its only argument:
object.instance_eval { |argument| argument == object } # => true
The instance_exec (opens new window) method differs in this regard: it passes its arguments to the block instead.
instance_exec
object.instance_exec :@variable do |name| instance_variable_get name # => :value end
Many languages feature a with statement that allows programmers to omit the receiver of method calls.
with
with can be easily emulated in Ruby using instance_eval (opens new window):
def with(object, &block) object.instance_eval &block end
The with method can be used to seamlessly execute methods on objects:
hash = Hash.new with hash do store :key, :value has_key? :key # => true values # => [:value] end
string
filename
lineno
block
obj
Read Articlehttps://develop.horje.com/learn/1434/reference