Search code examples
rubybackwards-compatibilityruby-2.1ruby-1.8

backward-compatibily code for ruby 1.8 and ruby 2.1 not working on File module


I need to write some code that need to run on ruby 1.8 and ruby 2.1, and specifically opening a file in UTF-8 encoding, so I naively wrote that

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

While it works on ruby 2.1, ruby 1.8 runs the code it shouldn't run and returns this error

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

I did some basic boolean testing it it that case it works fine

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

Can someone explain me the issue and how to solve it ?

thanks


Solution

  • The code is parsed before execution, and is parsed as a whole, so syntax errors aren't allowed even in dead code.

    Solution to your problem would be using old syntax for hashes so your code should look like this:

    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