我已经构建了一个应该在终端中运行的ruby脚本.
$ ruby script.rb
Run Code Online (Sandbox Code Playgroud)
我有一些特定于更新版本的ruby的代码,所以我在页面顶部添加了一个ruby版本检查:
abort("You're using ruby #{RUBY_VERSION}. Please use version 2.1 or newer") if (RUBY_VERSION.to_f < 2.1)
Run Code Online (Sandbox Code Playgroud)
我仔细检查了代码行irb,似乎在通过RVM更改ruby版本时工作.
但是,当我运行ruby脚本文件,比如ruby 1.8.7时,脚本会出现以下错误:
$ ruby script.rb
script.rb:6: odd number list for Hash
option1: 'some options',
^
script.rb:6: syntax error, unexpected ':', expecting '}'
option1: 'some options',
^
script.rb:6: syntax error, unexpected ',', expecting $end
Run Code Online (Sandbox Code Playgroud)
如果我没有在文件顶部进行版本检查,这将是预期的行为.
为什么版本检查在下一行代码之前没有执行?有没有办法在继续执行其余代码之前强制执行ruby检查?
我的完整档案是:
#!/usr/bin/env ruby
abort("You're using ruby #{RUBY_VERSION}. Please use version 2.1 or newer") if (RUBY_VERSION.to_f < 2.1)
options = {
option1: 'some options',
option2: 'some more options',
option3: 'other options'
}
Run Code Online (Sandbox Code Playgroud)
该错误发生在ruby解析器上.在ruby中,带符号的1.8.7哈希必须用hashrockets编写,{ :option => 'some options'}因为速记{ option: '' }仅在ruby 1.9中引入
为了更好地解释它,ruby必须在执行任何操作之前解析整个文件.因此,您的版本检查不会被执行,因为您的文件具有无效的ruby 1.8语法.