Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby word array as hash?

Ruby has something called a word array

fruits = %w(Apple Orange Melon)

becomes

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

is there anyway I can also use Ruby's word array as a hash?

fruits["Apple"] would return 0, fruits["Orange"] 1 and so forth. Or do I have to declare this as a hash?

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

The objective is to be able to save a field as a integer, but to have it's representation as a string on Rails.

like image 590
Clash Avatar asked Oct 17 '13 12:10

Clash


2 Answers

Hash[%w(Apple Orange Melon).each_with_index.to_a]  
# => {"Apple"=>0, "Orange"=>1, "Melon"=>2}
like image 144
Arup Rakshit Avatar answered Oct 07 '22 08:10

Arup Rakshit


Here is another one:

fruits = %w(Apple Orange Melon)
fruit_hash = Hash[[*fruits.each_with_index]]
like image 40
hirolau Avatar answered Oct 07 '22 09:10

hirolau