What is the easiest way to convert a range of 1..10 to a hash of the following format?
1..10
{ 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.
map
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}" }
What about:
h = {} (1..10).each {|x| h[x] = "£#{x}"}
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
h[100]
Source: https://habr.com/ru/post/894821/More articles:Non-UI BDD for Android - androidWhy is it not cleaning ClearAll ["Global` *"] from the user colors of the local variables of the palette? - wolfram-mathematicaCQRS naming conventions - naming-conventionsMaking Django Commit - djangoAssigning the value of one text field to another - jqueryMySQL query log standard input - mysqlOverriding functions with path-dependent type parameters - scalaWhy does ASP.NET allow assembly references differently? - asp.net3D geometry - c ++Django ORM queries do not allow selection of new objects - pythonAll Articles