Ruby字符数组作为哈希?

时间:2013-10-17 12:36:10

标签: ruby-on-rails ruby

Ruby有一种称为单词数组的东西

fruits = %w(Apple Orange Melon)

变为

fruits = ["Apple", "Orange", "Melon"]
无论如何,我还可以使用Ruby的单词数组作为哈希吗?

fruits["Apple"]将返回0,fruits["Orange"] 1等等。或者我必须将其声明为哈希?

fruits_hash = {
  'Apple' => 0,
  'Orange' => 1,
  'Melon' => 2,
}

目标是能够将字段保存为整数,但要将其表示为Rails上的字符串。

4 个答案:

答案 0 :(得分:12)

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

答案 1 :(得分:5)

这是另一个:

fruits = %w(Apple Orange Melon)
fruit_hash = Hash[[*fruits.each_with_index]]

答案 2 :(得分:5)

您的案件实际上并不需要Hash。在不同的情况下需要哈希,例如。表达如下数据:

{ Apple: :Rosaceae,
  Orange: :Rutaceae,
  Melon: :Cucurbitaceae } # botanical family

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

您不需要仅仅表达顺序的Hash es,例如{ 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!" }      

答案 3 :(得分:2)

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