假设我有两个字符串常量
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]
显然不起作用。
发布于 2016-11-09 10:07:15
KEY1:
是:KEY1 =>
的语法糖,所以实际上是以符号作为键,而不是常量。
若要将实际对象作为键,请使用散列火箭符号:
stories = {
KEY1 => { title: "The epic run" },
KEY2 => { title: "The epic fail" }
}
stories[KEY1]
#=> {:title=>"The epic run"}
https://stackoverflow.com/questions/40504296
复制相似问题