0

How would I create a hash with numbers as keys under the new ruby syntax? for example {abc: 123} creates a hash with the symbol abc as the key, but {123: 'abc' } throws an exception (as does {123.to_sym: 'abc'}. The exception I see is syntax error, unexpected '}', expecting $end. I can do hash[123] = 'abc' or Hash[123, 200], and could do {123 => 'abc'} under the old syntax but don't see how to create {123: 'abc'} under the new JSON style syntax.

Sully
  • 14,672
  • 5
  • 54
  • 79
d-coded
  • 413
  • 3
  • 9
  • You don't, AFAIK. The new syntax is syntactic sugar for a specific construct, symbols, and numbers don't turn in to symbols. – Dave Newton Jan 10 '13 at 19:17
  • The JavaScript-style notation only works with [some](http://stackoverflow.com/a/8675314/479863) [symbols](http://stackoverflow.com/a/10004344/479863), if your key isn't a symbol or is a symbol but not a valid label, then you have to use the hashrocket. – mu is too short Jan 10 '13 at 19:29
  • possible duplicate of [Is there any difference between the \`:key => "value"\` and \`key: "value"\` hash notations?](http://stackoverflow.com/questions/8675206/is-there-any-difference-between-the-key-value-and-key-value-hash-no) – mu is too short Jan 10 '13 at 19:29

2 Answers2

1

You can't. The syntax is for keys which are Symbols that are also valid Ruby identifiers. 123 is a Fixnum, not a Symbol, and even if it were a Symbol, it still wouldn't be a valid Ruby identifier.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • bummer, but thanks for taking the time to answer Jörg. Seems like there should be a simple way to convert, but I couldn’t figure it out. I'm going to keep this open for a little bit to see if anyone else has a different take. If not I'll give you credit for the answer since I'm also leaning toward it not being possible. – d-coded Jan 10 '13 at 20:05
0

you can consider 123 is already a symbol because 123 is as unique as a symbol. so {123: "abc"}

is not possible.

sunny1304
  • 1,684
  • 3
  • 17
  • 30