7

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.

Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
Maxim Veksler
  • 29,272
  • 38
  • 131
  • 151

1 Answers1

18

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"}
Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145