Assuming I have 2 strings constants
KEY1 = "Hello"
KEY2 = "World"
I would like to create a hash using these constants as key values.
Trying something like this:
stories = {
KEY1: { title: "The epic run" },
KEY2: { title: "The epic fail" }
}
Doesn't seem to work
stories.inspect
#=> "{:KEY1=>{:title=>\"The epic run\"}, :KEY2=>{:title=>\"The epic fail\"}}"
and stories[KEY1]
obviously doesn't work.
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.
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.
Hashes use keys to identify values, A key can be almost any object (String, Integer, Symbol, Object)
KEY1:
is the syntax sugar to :KEY1 =>
, so you're actually having symbol as key, not constant.
To have actual object as a key, use hash rocket notation:
stories = {
KEY1 => { title: "The epic run" },
KEY2 => { title: "The epic fail" }
}
stories[KEY1]
#=> {:title=>"The epic run"}
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