【问题标题】:In Ruby is it possible to create a local variable explicitly在 Ruby 中是否可以显式创建局部变量
【发布时间】: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


    【解决方案1】:

    根据myPerl 文档,我认为您正在 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】:

      小心! (相关,虽然不是完全你在问什么......)

      变量范围的规则在 1.8 和 1.9 之间发生了变化。见Variable Scope in Blocks

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-22
        • 1970-01-01
        • 2011-01-25
        • 2011-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-17
        相关资源
        最近更新 更多