In Ruby, I would like to select a default object for a block.
An example in Actionscript is:
with (board) {
length = 66;
width = 19;
fin_system = 'lockbox';
}
Which is equivalent to:
board.length = 66;
board.width = 19;
board.fin_system = 'lockbox';
Here is the documentation for this statement in Actionscript: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/statements.html#with
How can I accomplish this in Ruby?
You can't accomplish that exactly in Ruby because
foo = bar
will always set afoo
local variable; it will never call afoo=
method. You can use tap as suggested.One solution to the larger design question would be to use a fluent interface:
It's up to you to decide if this pattern suits your use case.
One way to implement it is with
instance_eval
, like that:But in some cases you have to use
self
(with operators and setting methods).You could try Object#tap with Ruby 1.9.
So in your case: