Maxim Veksler Maxim Veksler - 1 year ago 103
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

#=> "{:KEY1=>{:title=>\"The epic run\"}, :KEY2=>{:title=>\"The epic fail\"}}"

obviously doesn't work.

Answer Source

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" }
#=> {:title=>"The epic run"}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download