Another Ruby 1.9.2 gotcha hashes are not arrays

In ruby 1.8.7, the following works

Michael-Mainguys-MacBook-Pro:~ michaelmainguy$ irb
ruby-1.8.7-p352 :001 > foo = {"foo","bar"}
=> {"foo"=>"bar"}
ruby-1.8.7-p352 :002 > foo["foo"]
=> "bar"
ruby-1.8.7-p352 :003 >


In 1.9.2, it fails rather curiously.

Michael-Mainguys-MacBook-Pro:~ michaelmainguy$ irb
ruby-1.9.2-p290 :001 > foo = {"foo","bar"}
SyntaxError: (irb):1: syntax error, unexpected ',', expecting tASSOC
foo = {"foo","bar"}
^
(irb):1: syntax error, unexpected '}', expecting $end
from /Users/michaelmainguy/.rvm/rubies/ruby-1.9.2-p290/bin/irb:16:in `
'
ruby-1.9.2-p290 :002 >


Matz/et-al, get it together... this is a pretty significant change and probably warrants a deprecation warning instead of a mysterious fail that in no way indicates what is really happening. This will seriously dampen adoption of the 1.9.x series of ruby for newbies who used the hash constructor the old (arguably incorrect) way.

Newbies, if you try to upgrade to ruby 1.9.2 and you get these strange error messages.... it means you where trying to create hashes by passing comma separated values... if you really wanted to create a hash the ruby way would be

foo = {"foo"=>"bar"}

or, for an array
foo = {"foo","bar"}

by doing {"foo","bar"}, ruby was helpfully (in 1.8.7) translating your call into
foo = Hash.new(["foo","bar"])... note, in the cases I'm finding this, the folks really wanted an array, but because it "kinda" worked, they didn't realize what had happened.

Comments

Anonymous said…
I'm not sure doing this is a good idea in the first place:

foo = {"foo","bar"}
dasil003 said…
There's a lot of pain in major version upgrades, and moving from Ruby 1.8 to 1.9 has quite a few challenges, especially wrt to dependencies. Given that this is always a trivial change to fix for both 1.8 and 1.9, I have a hard time supporting idea that it needs to have an extended sunset. Might as well get it out of the way right now.

Popular posts from this blog

Please use ANSI-92 SQL Join Syntax

The difference between Scalability, Performance, Efficiency, and Concurrency explained

the myth of asynchronous JDBC