微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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中设置的值创建目标哈希…

原文地址:https://www.jb51.cc/ruby/265099.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐