2

There is a weird issue with Ruby 1.9.2's new hash syntax. How can I put any Object as key in hash in 1.9.2?

in 1.8.7 hash it works:

a="b" 
{"a" => "some",a => "another value",:a => "3rd value"}

But in 1.9.2 > We can't (or how can we if I'm wrong?")

1.9.2 hash:

{a: "some"} =>  {:a=>"s"} #it convert to old hash format

but

a="a" 
{a: "..."} # This doesn't work

{"a": "some value"} => syntax error, unexpected '}', expecting $end
from /home/naveed/.rvm/rubies/ruby-1.9.2-p290/bin/irb:16:in `<main>'

{1: "s"} =>

SyntaxError: (irb):11: syntax error, unexpected ':', expecting tASSOC {1: "s"}
user229044
  • 232,980
  • 40
  • 330
  • 338
Naveed
  • 11,057
  • 2
  • 44
  • 63
  • You know that the old syntax is still valid in 1.9, right? It's not a replacement, it's an addition. – sepp2k Apr 24 '12 at 08:04
  • Yeah old syntax is still here and it will be..I don't like to put too many rockets in my code :) => => => Dusss Duss – Naveed Apr 24 '12 at 08:18
  • possible duplicate of [Is there any difference between `:key => "value"` and `key: "value"` assignments?](http://stackoverflow.com/questions/8675206/is-there-any-difference-between-key-value-and-key-value-assignments) – Andrew Marshall Jul 29 '12 at 16:18

2 Answers2

6

In Ruby 1.9 you are allowed to put colon : only after symbols that are used as keys!

Any object can use the arrow =>, even symbols.

jdoe
  • 15,665
  • 2
  • 46
  • 48
  • {a:"s","a"=>"d"} don't looks pretty +1 for ": only after symbols " – Naveed Apr 24 '12 at 08:20
  • Rails extensively uses symbols as keys, so appearing hashes as yours isn't too probable. But of course, Rails isn't the only Ruby's application... – jdoe Apr 24 '12 at 08:45
3

To say this another way, the new feature isn't a new general hash syntax, it's a specific tweak for writing hashes where the keys are symbol literals. {a: 1} is just a shortcut for {:a => 1}, and that's all. If you have anything else as keys, you have to use the regular syntax.

user229044
  • 232,980
  • 40
  • 330
  • 338
glenn mcdonald
  • 15,290
  • 3
  • 35
  • 40