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

时间:2010-06-28 17:20:33

标签: ruby dry

我是红宝石的新手。有什么办法可以缩短这段代码吗?感谢

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

3 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:3)

我想你可以使用Enumerable#inject

plans.each do |plan|
  total = [:landline, :vpn, :other_networks, :gprs, :sms, :mms, :internat_calls_zone_1, :internat_calls_zone_2].inject(0) { |t, method| t + plan.send(method).to_f * @landline.send(method).to_f }
  if total < @total
    @total = total
    @plan_new = plan
  end
end

答案 2 :(得分:1)

刚刚出头:

plans.each do |plan|
  total = [
    :landline, :vpn, :other_networks, :gprs, :sms, :mms, 
    :internat_calls_zone_1, :internat_calls_zone_2
  ].inject(0) {|sum,key|
    sum += plan.send(key).to_f * instance_variable_get(:"@#{key}").to_f
    sum
  }

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