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
.
#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 .
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.
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.
Use hash rocket syntax:
h = { "a" => 123 } #=> {"a"=>123} h['a'] #=> 123
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