在 Ruby 哈希中使用常量作为键

7
假设我有两个字符串常量。
KEY1 = "Hello"
KEY2 = "World"

我想使用这些常量作为键值来创建一个哈希表。
尝试像这样做:
```ruby hash = { constant1: value1, constant2: value2, constant3: value3 } ```
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个回答

18
< p > KEY1: 是语法糖,等同于:KEY1 =>,因此你实际上是将symbol作为键,而不是常量。

要使用实际对象作为键,请使用 hash rocket 符号:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接