加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby eval在irb中与文件中的行为不同

发布时间:2020-12-17 04:03:03 所属栏目:百科 来源:网络整理
导读:此代码适用于irb: irb(main):037:0 eval -EOSirb(main):038:0" #{attribute} = "host"irb(main):039:0" puts machineirb(main):040:0" EOShost= nilirb(main):041:0 puts machinehost= nilirb(main):042:0 puts attributemachine= nilirb(main):043:0 但是,
此代码适用于irb:

irb(main):037:0> eval <<-EOS
irb(main):038:0" #{attribute} = "host"
irb(main):039:0" puts machine
irb(main):040:0" EOS
host
=> nil
irb(main):041:0> puts machine
host
=> nil
irb(main):042:0> puts attribute
machine
=> nil
irb(main):043:0>

但是,当我尝试执行与ruby脚本相同的代码时,我收到以下错误:

../autosys/convert_jil_to_zapp.rb:40: undefined local variable or method `machine' for main:Object (NameError)
        from ../autosys/convert_jil_to_zapp.rb:29:in `each_line'
        from ../autosys/convert_jil_to_zapp.rb:29
        from ../autosys/convert_jil_to_zapp.rb:27:in `each'
        from ../autosys/convert_jil_to_zapp.rb:27
pi929c1n10 /ms/user/h/hirscst/ruby/autosys 77$gvim try.rb
pi929c1n10 /ms/user/h/hirscst/ruby/autosys 78$chmod +x try.rb
pi929c1n10 /ms/user/h/hirscst/ruby/autosys 79$./try.rb
host
./try.rb:8: undefined local variable or method `machine' for main:Object (NameError)

有谁能解释为什么?

解决方法

这是因为在运行eval时尚未定义机器变量.一个更简洁的例子:

适用于IRB,但不适用于脚本

eval 'x = 3'
puts x # throws an exception when run as a script
=> 3

适用于IRB和脚本

x = 1
eval 'x = 3'
puts x
=> 3

至quote Matz:

local variables should be determined at compile time,thus local
variables defined first in the eval’ed string,can only be accessed from
other eval’ed strings. In addition,they will be more ephemeral in
Ruby2,so that these variables will not be accessed from outside.

不同之处在于IRB中的所有内容都被评估,因此它们都在相同的范围内.也就是说,你基本上是在IRB中这样做的:

eval 'x = 3'
eval 'puts x'

它既适用于IRB,也适用于脚本.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读