According to The Well Grounded Rubyist:
Ruby allows a special form of symbol representation in the hash-key position, with the colon after the symbol instead of before it and the hash separator arrow removed. In other words, this:
hash = { :name => "David", :age => 49 }
can also be written like this:
hash = { name: David, age: 49 }
I have tried the preceding code in ruby 1.8.7 and 1.9.2 - It is not working. What am I doing wrong?
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.
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.
Prerequisites: Hashes and Arrays in Ruby Arrays and hashes are data structures that allow you to store multiple values at once.
Public Instance Methods Returns true if hash is subset of other or equals to other. Equality—Two hashes are equal if they each contain the same number of keys and if each key-value pair is equal to (according to Object#== ) the corresponding elements in the other hash. The orders of each hashes are not compared.
The new hash syntax in Ruby 1.9 still requires that strings be quoted, so instead of David
you need "David"
.
Try this:
hash = { name: "David", age: 49 }
If the book used the bare word David
without quotation marks, it is wrong. You might be interested in reading some of the other errata.
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