在循环中设置Ruby对象的多个属性

时间:2017-07-08 09:59:00

标签: ruby-on-rails ruby

我有一组包含属性的类(firstsecondthird等。 我需要经历所有"甚至"属性(即secondfourthsixth等)并对其进行一些修正:

report.first = Calculate('1')

report.second = Calculate('2')
report.second *= 0.9 if requireCorrection && report.second > 5

report.third = Calculate('3')

report.fourth = Calculate('4')
report.fourth *= 0.9 if requireCorrection && report.fourth > 5

report.fifth = Calculate('5')

report.sixth = Calculate('6')
report.sixth *= 0.9 if requireCorrection && report.sixth > 5

# etc.

正如您所看到的,我对每个"甚至"都有完全相同的代码。属性,除了不同的属性名称。有没有办法避免代码中的这种重复(我总共有大约50个属性)?

1 个答案:

答案 0 :(得分:1)

您可以使用Object#send通过将方法名称指定为字符串或符号来调用report上的任意方法:

def make_correction(report, which_method)
  current_value = report.send(which_method)
  current_value *= 0.9 if current_value > 5
  report.send "#{which_method}=", current_value
end

方法名称firstsecondthird等不容易实现自动化,但如果将方法重命名为item_1,{{1等等,您可以使用循环来处理所有这些:

item_2

如果方法名称需要保持不变,您仍然可以简化代码:

(1..50).each do |i|
  report.send "item_#{i}=", Calculate(i.to_s)

  if i.even?
    make_correction(report, "item_#{i}") if require_correction
  end
end