向后兼容的代码为红宝石1.8和红宝石2.1不工作文件模块

问题描述:

我需要编写一些代码,需要在红宝石1.8和红宝石2.1上运行,并特别打开UTF-8编码的文件,所以我天真地写这向后兼容的代码为红宝石1.8和红宝石2.1不工作文件模块

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 

虽然它可以在2.1红宝石,红宝石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 

我做了一些基本的布尔测试它,它这种情况下,它工作正常

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