我迷路了。我需要使用与1到10之间的数字对应的键创建一个哈希。结果应该是这样的:
my_hash = {1 => "", 2 => "", 3 => ""...}
我有
h = Hash.new
请至少给我一种方法,我需要"价值观"后来,现在我只需要一个带键的哈希值,稍后我会推送值。谢谢!
答案 0 :(得分:1)
h = Hash.new
(1..10).each {|count| h[count] = ''}
答案 1 :(得分:1)
怎么样:
(1..10).map { |x| [x, ''] }.to_h
或者:
{}.tap { |h| 1.step(10) { |i| h[i] = '' } }
或者:
(1..10).zip(Array.new(10) { '' }).to_h
答案 2 :(得分:1)
还有一些选择:
(1..10).each_with_object({}) { |i, h| h[i] = '' }
10.times.each_with_object({}) { |i, h| h[i + 1] = '' }
1.upto(10).each_with_object({}) { |i, h| h[i] = '' }
# Or if you think each_with_object is heresy...
(1..10).inject({}) { |h, i| h.merge!(i => '') } # merge! to avoid wasteful copying
10.times.inject({}) { |h, i| h.merge!(i + 1 => '') }
1.upto(10).inject({}) { |h, i| h.merge!(i => '') }