Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby new hash colon notation with string keys

Tags:

ruby

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" 
like image 924
phillee Avatar asked Sep 06 '12 15:09

phillee


People also ask

How do I add a key to a hash in Ruby?

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.

How do you make hash hashes 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.

What does hash new do in Ruby?

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.

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.


1 Answers

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}  
like image 50
Chowlett Avatar answered Sep 17 '22 18:09

Chowlett