简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM