Ruby Language Implementing "with" using instance evaluation


Example

Many languages feature a with statement that allows programmers to omit the receiver of method calls.

with can be easily emulated in Ruby using instance_eval:

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