Ruby – Why is the text “2e8” treated as a string by YAML on Mac and float in Ruby on Linux?

Why is the text “2e8” treated as a string by YAML on Mac and float in Ruby on Linux?… here is a solution to the problem.

Why is the text “2e8” treated as a string by YAML on Mac and float in Ruby on Linux?

For the same

ruby version, the same YAML parser engine Psych (but different minor versions), but different operating systems (Mac vs Linux), the text “2e8" is considered String on Mac, but Float (200000000.0) on Linux )。 Why? How can I fix this so that they exhibit the same behavior?

    For Mac: Darwin 12.4.0

  • Darwin kernel version 12.4.0: root: xnu-2050.24.15~1/RELEASE_X86_64 x86_64

    require "yaml"
    RUBY_VERSION # => "1.9.3"
    YAML::ENGINE.yamler # => "psych"
    Psych::VERSION # => "1.2.2"
    
    Psych.load("2e8") # => "2e8"
    YAML.load("2e8") # => "2e8"
    YAML.load("'2e8'") # => "2e8"
    
  • For Linux: Linux 2.6.18-238.el5 #1 SMP x86_64 GNU/Linux

    require "yaml"
    RUBY_VERSION # => "1.9.3"
    YAML::ENGINE.yamler # => "psych"
    Psych::VERSION # => "1.2.1"
    
    Psych.load("2e8") # => 200000000.0
    YAML.load("2e8") # => 200000000.0
    YAML.load("'2e8'") # => "2e8"
    

I know that adding quotes ‘2e8' produces the same behavior, but this text is part of the dump generated on Mac and these quotes are not placed.

Solution

The difference is the psych version.

Here are the relevant commits: https://github.com/tenderlove/psych/commit/2422a9fc3aeff3c60c6510efbf655a34218c7605

You’re about two years behind the latest version, so I’m suggesting if you can update your dependencies on the project.

How did I find this? Use GitHub’s excellent comparison features: https://github.com/tenderlove/psych/compare/v1.2.1…v1.2.2

Related Problems and Solutions