gpt4 book ai didi

ruby-on-rails - 在 ruby​​ on rails 中使用键和值创建动态哈希

转载 作者:数据小太阳 更新时间:2023-10-29 06:59:22 26 4
gpt4 key购买 nike

我正在尝试使用动态键和各自的值创建哈希。比如像这样

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,'-0.57E2',9(18)>}

如有其他优化方案,不胜感激

最佳答案

您将在每次迭代时使用新哈希重新分配 test。你应该添加它,而不是

test ={i => s1.power}

你应该这样做:

test[i] = s1.power

设置i的值到s1.power


如果您想保留给定键的所有值的数组,我建议采用以下(更像 ruby​​ 风格)解决方案:

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 }

我在这里做的是:

  1. 找到与当前s相关的hour_idx(我假设只有一个这样的项目)
  2. 根据s.type创建所有相关值的数组(如果是'M'所有_power的数组s.sgs,对于 'L' 您需要的任何 map ,否则为 nil)
  3. 使用#1 和#2 中设置的值创建目标散列...

关于ruby-on-rails - 在 ruby​​ on rails 中使用键和值创建动态哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23979535/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com