Over a million developers have joined DZone.

A Ruby Mystery that May Alienate New Ruby Users


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.

Source: http://mikemainguy.blogspot.com/2011/09/another-ruby-192-gotcha-hashes-are-not.html



Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}