在ruby hash中使用常量作为键

时间:2016-11-09 10:05:34

标签: ruby hash

假设我有2个字符串常量

KEY1 = "Hello"
KEY2 = "World"

我想使用这些常量作为键值来创建哈希。

尝试这样的事情:

stories = {
  KEY1: { title: "The epic run" },
  KEY2: { title: "The epic fail" }
}

似乎无法正常工作

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

stories[KEY1]显然无法正常工作。

1 个答案:

答案 0 :(得分:9)

KEY1::KEY1 =>的语法糖,因此您实际上将 符号 作为键,而不是常量。

要将实际对象作为键,请使用散列火箭表示法:

stories = {
  KEY1 => { title: "The epic run" },
  KEY2 => { title: "The epic fail" }
}
stories[KEY1]
#=> {:title=>"The epic run"}