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"
Hash literals use the curly braces instead of square brackets and the key value pairs are joined by =>. For example, a hash with a single key/value pair of Bob/84 would look like this: { "Bob" => 84 }. Additional key/value pairs can be added to the hash literal by separating them with commas.
Most commonly, a hash is created using symbols as keys and any data types as values. All key-value pairs in a hash are surrounded by curly braces {} and comma separated. Hashes can be created with two syntaxes. The older syntax comes with a => sign to separate the key and the value.
2. new : This method returns a empty hash. If a hash is subsequently accessed by the key that does not match to the hash entry, the value returned by this method depends upon the style of new used to create a hash.
We can merge two hashes using the merge() method. When using the merge() method: Each new entry is added to the end. Each duplicate-key entry's value overwrites the previous value.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With