ruby-on-rails – 在rails上的ruby中创建带键和值的动态哈希

我正在尝试使用动态密钥和相应的值创建哈希.比如这样
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中设置的值创建目标哈希…

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...