7

假设我有 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]不起作用。

4

1 回答 1

16

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

要将实际对象作为键,请使用哈希火箭符号:

stories = {
  KEY1 => { title: "The epic run" },
  KEY2 => { title: "The epic fail" }
}
stories[KEY1]
#=> {:title=>"The epic run"}
于 2016-11-09T10:07:15.047 回答