加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby:使用相同的名称乘以许多变量

发布时间:2020-12-17 03:58:01 所属栏目:百科 来源:网络整理
导读:我是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.
我是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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读