Ruby eval在irb和文件中的行为不同 [英] Ruby eval behaves differently in irb versus in a file

查看:67
本文介绍了Ruby eval在irb和文件中的行为不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码在irb中有效:

This code works in 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脚本相同的代码时,出现以下错误:

however when I try to execute the same code as a ruby script I get the following error:

../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 时,尚未定义> machine 变量。一个更简洁的示例:

It's because the machine variable was not already defined when eval was run. A more concise example:

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



在IRB中作为脚本工作



Works in IRB and as a script

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

quote Matz


局部变量应在编译时确定,因此只能在其他评估字符串中从
中访问在评估字符串中首先定义的局部
变量。另外,在
Ruby2中它们将更短暂,因此不会从外部访问这些变量。

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中执行此操作:

The difference is that in IRB everything is being eval'd, so it's all in the same scope. That is, you're essentially doing this in IRB:

eval 'x = 3'
eval 'puts x'

在IRB和脚本中都可以工作。

Which works both in IRB and as a script.

这篇关于Ruby eval在irb和文件中的行为不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆