将Ruby单词数组转换为哈希表?

5
Ruby有一种叫做“词数组”的东西。
fruits = %w(Apple Orange Melon)

变成

fruits = ["Apple", "Orange", "Melon"]

有没有办法将Ruby的单词数组用作哈希表呢?fruits["Apple"] 将返回0,fruits["Orange"] 将返回1等等。还是我必须将其声明为哈希表?请注意保留HTML标记。
fruits_hash = {
  'Apple' => 0,
  'Orange' => 1,
  'Melon' => 2,
}

目标是将一个字段保存为整数,但在Rails中将其表示为字符串。

4个回答

12
Hash[%w(Apple Orange Melon).each_with_index.to_a]  
# => {"Apple"=>0, "Orange"=>1, "Melon"=>2}

1
我更喜欢这个。 - Bala

5
这是另一个例子:
fruits = %w(Apple Orange Melon)
fruit_hash = Hash[[*fruits.each_with_index]]

5
您的情况实际上不需要使用Hash。哈希在不同情况下是必需的,例如用于表达类似以下数据的情况:
{ Apple: :Rosaceae,
  Orange: :Rutaceae,
  Melon: :Cucurbitaceae } # botanical family

或者

{ Apple: 27,
  Orange: 50,
  Melon: 7 } # the listing of greengrocer's stock

您不需要仅表达顺序的哈希表,例如{ Apple: 1, Orange: 2, Melon: 3 } -- 只使用普通数组[ :Apple, :Orange, :Melon ]即可:

a = :Apple, :Orange, :Melon
a.index :Orange #=> 1

此外,我建议您在某些情况下使用Symbol而不是String,特别是对于苹果、橙子、甜瓜等东西。字符串适用于推文、消息正文、商品描述等内容...

{ Apple: "Our apples are full of antioxidants!",
  Orange: "Our oranges are full of limonene and vitamin C!",
  Melon: "Our melons are sweet and crisp!" }      

2
Hash[fruits.zip((0...fruits.length).to_a)]
=> {"Apple"=>0, "Orange"=>1, "Melon"=>2}

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