In Ruby is it possible to create a local variable explicitly

寵の児 提交于 2020-01-11 10:17:33

问题


e.g.

x = 123
p = Proc.new {
  x = 'I do not want change the value of the outer x, I want to create a local x'
}

In Ruby Is there something the same as "my" keyword in Perl ?


回答1:


As per the Perl documentation of my,I think you are looking for something like below in 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



回答2:


Beware! (Related, though not exactly what you're asking...)

The rules for variable scope changed between 1.8 and 1.9. See Variable Scope in Blocks

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

behaves differently in the different versions. If you declare a variable in a block's || that has the same name as a variable outside the block, then in 1.8 it will change the value of the outer variable, and in 1.9 it will not.



来源:https://stackoverflow.com/questions/18599758/in-ruby-is-it-possible-to-create-a-local-variable-explicitly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!