在Ruby中,我想为块选择一个默认对象.
Actionscript中的一个例子是:
with (board) {
length = 66;
width = 19;
fin_system = 'lockbox';
}Run Code Online (Sandbox Code Playgroud)
这相当于:
board.length = 66;
board.width = 19;
board.fin_system = 'lockbox';Run Code Online (Sandbox Code Playgroud)
以下是Actionscript中此语句的文档:http: //livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/statements.html#with
我怎样才能在Ruby中实现这一目标?
Hash.new.tap do |h|
h[:name] = "Mike"
h[:language] = "Ruby"
end
#=> {:name=>"Mike", :language=>"Ruby"}
Run Code Online (Sandbox Code Playgroud)
您可以使用Ruby 1.9 尝试Object#tap.
所以在你的情况下:
board.tap do |b|
b.length = 66;
b.width = 19;
b.fin_system = "lockbox"
end
Run Code Online (Sandbox Code Playgroud)