Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Hash with string keys by default

When I do the following:

h = { "a": 123 } 

Ruby converts the key to a symbol automatically.

h[:a]  # => 123 h["a"] # => nil 

How can I prevent this behaviour? I created the hash with a string key, and would like to keep it that way without always having to call Hash#stringify_keys.

like image 704
Joerg Avatar asked Oct 21 '16 09:10

Joerg


People also ask

How do you represent a hash in Ruby?

#Symbols must be valid Ruby variable names and always start with a colon (:). In Ruby, symbols are immutable names primarily used as hash keys or for referencing method names. Recall that hashes are collections of key-value pairs, where a unique key is associate… We can also iterate over hashes using the .

What is a Ruby hash?

In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type. In Hash, the order of returning keys and their value by various iterators is arbitrary and will generally not be in the insertion order.

What is key and value in hash?

Entries in a hash are often referred to as key-value pairs. This creates an associative representation of data. Most commonly, a hash is created using symbols as keys and any data types as values.


1 Answers

Use hash rocket syntax:

h = { "a" => 123 } #=> {"a"=>123} h['a'] #=> 123 
like image 141
Andrey Deineko Avatar answered Sep 21 '22 12:09

Andrey Deineko