Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby/Rails: Converting a range into a hash

What is the simplest way to convert the range 1..10 into a hash of the following format?

{
  1 => '£1',
  2 => '£2',
  # ...
}

I have tried doing this with map, but end up with an array of hashes rather than a single hash.

Thanks.

like image 338
gjb Avatar asked Aug 11 '11 12:08

gjb


3 Answers

Hash[(1..10).map { |num| [num, "£#{num}"] }]

or

(1..10).inject({}) { |hash, num| hash[num] = "£#{num}"; hash }

or in Ruby 1.9

(1..10).each_with_object({}) { |num, hash| hash[num] = "£#{num}" } 
like image 102
rubyprince Avatar answered Oct 12 '22 03:10

rubyprince


How about:

h = {}
(1..10).each {|x| h[x] = "£#{x}"}
like image 21
grifaton Avatar answered Oct 12 '22 04:10

grifaton


another way

h = Hash.new { |hash, key| hash[key] = "£#{key}" }

each element will have appropriate value hovever it will also respond to h[100] what might cause bugs

like image 43
Bohdan Avatar answered Oct 12 '22 02:10

Bohdan