Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Multiply many variables with the same name

Tags:

ruby

dry

I'm new to ruby. Is there any way how can I shorten this code? Thanks

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
like image 728
Sergey Avatar asked Dec 22 '22 01:12

Sergey


1 Answers

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
like image 113
rampion Avatar answered Dec 24 '22 15:12

rampion