Ruby Language Metaprogramming Implementing "with" using instance evaluation

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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


Got any Ruby Language Question?