Ruby / Rails: Converting a Range to a Hash

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

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

I tried to do this using map , but in the end we get an array of hashes, not just one hash.

Thanks.

+6
source share
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}" } 
+12
source

What about:

 h = {} (1..10).each {|x| h[x] = "£#{x}"} 
+2
source

another way

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

each element will have a corresponding hoverver value, it will also respond to h[100] , which may cause errors

+1
source

Source: https://habr.com/ru/post/894821/


All Articles