For example, let’s say I have
block = proc { |n| "#{downcase} #{n}" }
Now I want to evaluate that block in the scope of a String, but pass that block a variable. I know how to do the first part:
"Foo".instance_eval(&block)
But how to also pass a variable to that block?
I tried
"Foo".instance_eval { block.call(3) }
But it didn’t work, it wasn’t in the scope of the String.
Use
instance_execinstead:So this will make it go:
and give you the
'foo 3'that you desire.The problem with this:
is that
selfwill be"Foo"inside{ block.call(3) }but not insideblock,blockwill retain whateverselfwas whenblockwas defined; there’s nothing inblock.call(3)that forces a context soselfdoesn’t change. For example, given this:When the proc is called,
selfwill becbecause that’s whatselfwas when the proc was defined (i.e. whenmwas called). Whatselfis inside theinstance_evalblock doesn’t have any effect onselfinside the proc.