Let’s say you have a class that has a debug method, and you call it repeteadly:
obj.debug("debugstring")
obj.debug(debug_val)
obj.debug(another_debug_val)
You could make this shorter by using the with method. This will evaluate the code inside the block in the context of the object it was called upon:
obj.with {
debug("debugstring")
debug(debug_val)
debug(another_debug_val)
}
This can make your code cleaner and simpler to understand.
Here’s the Ruby equivalent: instance_eval, and a snippet of code showing how to use it:
File.open("some.file") do |file|
file.instance_eval do
puts "this goes into the file"
puts "same as this"
end
end
By calling instance_eval, the puts method calls become file.puts. Nice, right?