24

Using ruby 1.9.3, string keys don't seem to work with Hash colon notation:

1.9.3p194 :005 > {abc: 5}
 => {:abc=>5} 

1.9.3p194 :004 > {'abc': 5}
SyntaxError: (irb):4: syntax error, unexpected ':', expecting tASSOC
{'abc': 5}
       ^

I think I'm running the right version of Ruby

1.9.3p194 :006 > RUBY_ENGINE
 => "ruby" 
1.9.3p194 :007 > RUBY_VERSION
 => "1.9.3" 
phillee
  • 2,227
  • 2
  • 19
  • 28

1 Answers1

42

That's correct - the new colon notation for hashes only works when the keys are symbols.

Sorry, that's just how it is.

Update: general symbols are supported using the new notation in ruby 2.2 and later (strings as keys still aren't):

irb
2.2.2 :001 > {'abc': 5}
=> {:abc=>5} 
Chowlett
  • 45,935
  • 20
  • 116
  • 150
  • 4
    Only works when the keys are *some* symbols. For example, you can't use it with `:$set` or `:'pan.cakes'`. – mu is too short Sep 06 '12 at 15:35
  • @muistooshort - Fair point. I suspected as much, but couldn't find evidence in pickaxe. Have you got a citation? – Chowlett Sep 06 '12 at 15:40
  • 1
    Thanks for the quick response. How are people handling this? Just using the rocket hash notation when you have a string? – phillee Sep 06 '12 at 16:02
  • I don't have a citation, I read the C source to figure out what's allowed because I couldn't find an authoritative definition. I think it is, more or less, `^[a-zA-Z_]\w*`. – mu is too short Sep 06 '12 at 16:03
  • 1
    @phillee: Yes, you have to use the hashrocket except for a certain set of symbols. We've been over this a few times already: http://stackoverflow.com/a/8675314/479863, http://stackoverflow.com/a/10004344/479863, and several others that I can't find right now. – mu is too short Sep 06 '12 at 16:05