在Ruby中,可以显式创建局部变量

例如

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”关键字相同的东西?

根据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之间变化。 请参见块中的变量范围

 x = 100 [1,2,3].each do |x| 

在不同的版本中表现不同。 如果在块的||中声明变量 与块外的变量同名,然后在1.8中它将改变外部变量的值,而在1.9中则不会。