【发布时间】:2013-09-07 03:06:14
【问题描述】:
例如
x = 123
p = Proc.new {
x = 'I do not want change the value of the outer x, I want to create a local x'
}
在 Ruby 中是否有与 Perl 中的“my”关键字相同的东西?
【问题讨论】:
标签: ruby variables block local proc
例如
x = 123
p = Proc.new {
x = 'I do not want change the value of the outer x, I want to create a local x'
}
在 Ruby 中是否有与 Perl 中的“my”关键字相同的东西?
【问题讨论】:
标签: ruby variables block local proc
根据my 的 Perl 文档,我认为您正在 Ruby 中寻找如下内容:-
x = 123
p = Proc.new {|;x|
x = 'I do not want change the value of the outer x, I want to create a local x'
}
p.call
# => "I do not want change the value of the outer x, I want to create a local x"
x # => 123
【讨论】:
小心! (相关,虽然不是完全你在问什么......)
变量范围的规则在 1.8 和 1.9 之间发生了变化。见Variable Scope in Blocks
x = 100
[1,2,3].each do |x|
在不同版本中表现不同。如果在块的 || 中声明变量与块外的变量同名,那么在 1.8 中它将更改外部变量的值,而在 1.9 中则不会。
【讨论】: