gpt4 book ai didi

ruby-on-rails - Ruby 变量如何以及何时实例化

转载 作者:数据小太阳 更新时间:2023-10-29 06:59:24 26 4
gpt4 key购买 nike

从 Rails 控制台:

development environment (Rails 3.2.9)
1.9.2p320 :001 > defined?(kol)
=> nil
1.9.2p320 :002 > if 1==2
1.9.2p320 :003?> kol = 'mess'
1.9.2p320 :004?> end
=> nil
1.9.2p320 :005 > defined?(kol)
=> "local-variable"
1.9.2p320 :006 > kol
=> nil

我的问题是,为什么即使条件 (1==2) 失败,变量 kol 也会被实例化为 nil

最佳答案

这与 Ruby 解释器读取代码的方式有关。

The assignment to the variable doesn't have to be executed; the Ruby interpreter just needs to have seen that the variable exists on the left side of an assignment. (Programming Ruby 1.9 & 2.0)

a = "never used" if false
[99].each do |i|
a = i # this sets the variable in the outer scope
end
a # => 99

"Ruby interpreter creates the variable even though the assignment isn't actually executed." http://www.jacopretorius.net/2012/01/block-variable-scope-in-ruby.html

关于ruby-on-rails - Ruby 变量如何以及何时实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15722325/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com