gpt4 book ai didi

Ruby:将多个同名变量相乘

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

我是 ruby 新手。有什么办法可以缩短这段代码吗?谢谢

plans.each do |plan|
total = plan.landline.to_f * @landline.to_f
total += plan.vpn.to_f * @vpn.to_f
total += plan.other_networks.to_f * @other_networks.to_f
total += plan.gprs.to_f * @gprs.to_f
total += plan.sms.to_f * @sms.to_f
total += plan.mms.to_f * @mms.to_f
total += plan.internat_calls_zone_1.to_f * @internat_calls_zone_1.to_f
total += plan.internat_calls_zone_2.to_f * @internat_calls_zone_2.to_f

if total < @total
@total = total
@plan_new = plan
end
end

最佳答案

plans.each do |plan|
total = [ :landline, :vpn, other_networks, :gprs, :sms, :mms, :internat_calls_zone_1 ].inject(0.0) do |partial_sum, term|
partial_sum + plan.send(term).to_f * instance_variable_get("@#{term}").to_f
end
if total < @total
@total = total
@plan_new = plan
end
end

关于Ruby:将多个同名变量相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3134603/

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