简体   繁体   中英

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.

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"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM