Generate hash for value 1 to 31 with ruby?
How can I generate ha开发者_Go百科sh something like this ?
{1 => 1, 2 => 2, 3 => 3}
from 1 to 31 with loop.
For example:
(1..31).inject({}) { |h, k| h[k] = k; h}
If you want a hash that works for all numbers, you can do it this way:
>> h = Hash.new { |h, k| h[k] = k } #=> {}
>> h[221] #=> 221
def generate_hash r
Hash[r.zip r]
end
generate_hash (1..31)
Another one-liner:
Hash[(1..31).map {|i| [i,i]}]
Try this
h = Hash.new()
for i in 1..31
h[i] = i
end
Also, the question did not specify whether the order is important, but if order is important, you might want to consider a different sorting options, as describe here
Sorting Hash of Hashes by value (and return the hash, not an array)
(1..31).inject({}) { |hash, item| hash.merge(item => item) }
Why are you doing this? Are you doing this because there's 31 days in a month?
Anyway:
hash = Hash.new() {|_, key| key if (1..31).include?(key) }
hash[1] # => 1
hash[31] # => 31
hash[32] # => nil
Edit: Now with code golfing from Michael Kohl!
My small contribution:
Hash[1.upto(31).zip 1.upto(31)]
or
Hash[(1.upto 31).zip(1.upto 31)]
精彩评论