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.
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}" }
How about:
h = {}
(1..10).each {|x| h[x] = "£#{x}"}
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
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