我正在尝试使用动态密钥和相应的值创建哈希.比如这样
- hash = {1 => 23.67,1 => 78.44,3 => 66.33,12 => 44.2}
像这样的1,2,12是数组索引.我希望这是可以理解的.我正在尝试使用ROR教程中的语法.
像这样
- test = Hash.new
- for i in 0..23
- if (s.duration.start.hour == array[i].hour)
- s.sgs.each do |s1|
- case s1.type.to_s
- when 'M'
- test ={i => s1.power} # here I am trying to create hash like give example in which i is for loop value
- when 'L'
- puts "to be done done"
- else
- puts "Not Found"
- end
- end
- end
- end
- end
更新的代码
- test = Hash.new
- for i in 0..23
- if (s.duration.start.hour == array[i].hour)
- s.sgs.each do |s1|
- case s.type.to_s
- when 'M'
- puts s1.power;
- test[i] = s1._power
- when 'L'
- puts "to be done"
- else
- puts "Not Found"
- end
- end
- end
- end
结果
在遍历
- for t in 0..array.size
- puts test[t]
- end
结果:
- t = 68.6 # which is last value
并期待
- t = 33.4
- t = 45.6 etc
样本日志
- after assign {23=>#<BigDecimal:7f3a1e9a6870,'0.3E2',9(18)>}
- before assign {23=>#<BigDecimal:7f3a1e9a6870,'0.2E2',9(18)>}
- after assign {23=>#<BigDecimal:7f3a1e9ce550,'-0.57E2',9(18)>}
- before assign {23=>#<BigDecimal:7f3a1e9ce550,9(18)>}
如果有任何其他优化的解决方案,那将是非常感谢
解决方法
您将在每次迭代时使用新哈希重新分配测试.你应该添加它,而不是
- test ={i => s1.power}
你应该做:
- test[i] = s1.power
这将key i的值设置为s1.power
如果你想保留给定键的所有值的数组,我会建议以下(更多ruby-ish)解决方案:
- hour_idx = array.find_index { |item| s.duration.start.hour == item.hour }
- values = case s.type.to_s
- when 'M'
- s.sgs.map(&:_power)
- when 'L'
- puts "to be done"
- else
- puts "Not Found"
- end
- test = { hour_idx => values }
我在这里做的是:
>找到与当前s相关的hour_idx(我假设只有一个这样的项目)>根据s.type创建一个包含所有相关值的数组(如果它是’M’是s.sgs的所有_power的数组,’L’表示你需要的任何地图,否则为nil)>使用#1和#2中设置的值创建目标哈希…