Maxim Veksler Maxim Veksler - 25 days ago 22
Ruby Question

Using constant as keys in ruby hash

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.

Answer

KEY1: is the shortcut 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"}
Comments