Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash syntax in Ruby [duplicate]

Tags:

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?

like image 522
grigoryvp Avatar asked Dec 30 '10 15:12

grigoryvp


People also ask

How do you write hash in Ruby?

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.

How do you add two hashes in Ruby?

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.

Can a hash have multiple values Ruby?

Prerequisites: Hashes and Arrays in Ruby Arrays and hashes are data structures that allow you to store multiple values at once.

How do you know if two hashes are equal Ruby?

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.


1 Answers

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.

like image 89
meagar Avatar answered Sep 19 '22 05:09

meagar