我需要写一些需要在ruby 1.8和ruby 2.1上运行的代码,并且专门打开一个UTF-8编码的文件,所以我天真地写了那个
if RUBY_VERSION > "1.9"
f = File.open('/usr/share/hwdata/pci.ids', encoding: "utf-8")
else
f = File.open('/usr/share/hwdata/pci.ids')
end
虽然它在 ruby 2.1 上工作,但 ruby 1.8 运行它不应该运行的代码并返回此错误
test_ruby_version.rb:8: syntax error, unexpected ':', expecting ')'
f = File.open('/usr/share/hwdata/pci.ids', encoding: "utf-8")
^
test_ruby_version.rb:8: syntax error, unexpected ')', expecting kEND
我做了一些基本的 bool 测试,以防它工作正常
if RUBY_VERSION > "1.9"
puts "this is displayed when running ruby 2"
end
if RUBY_VERSION < "2.0"
puts "this is displayed when running ruby 1.9 or less"
end
if RUBY_VERSION < "1.8"
puts "this is displayed when running ruby 1.7 or less"
end
有人可以向我解释这个问题以及如何解决吗?
谢谢
最佳答案
代码在执行前解析,作为一个整体解析,所以即使是死代码也不允许有语法错误。
您的问题的解决方案是对散列使用旧语法,因此您的代码应如下所示:
if RUBY_VERSION > "1.9"
f = File.open('/usr/share/hwdata/pci.ids', :encoding => "utf-8")
else
f = File.open('/usr/share/hwdata/pci.ids')
end
关于ruby - ruby 1.8 和 ruby 2.1 的向后兼容代码不适用于文件模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46644787/