Using constant as keys in ruby hash
Asked Answered
S

1

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.

Surinam answered 9/11, 2016 at 10:5 Comment(0)
S
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"}
Sunstroke answered 9/11, 2016 at 10:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.