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.
Hash[%w(Apple Orange Melon).each_with_index.to_a]
# => {"Apple"=>0, "Orange"=>1, "Melon"=>2}
Here is another one:
fruits = %w(Apple Orange Melon)
fruit_hash = Hash[[*fruits.each_with_index]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With