【发布时间】:2015-02-16 21:32:32
【问题描述】:
困惑?
我有 4 种这样的方法:
def email_proposed_water_cost
total = 0.00
if self.estimate_water.count == 12
(1..12).each_with_index do |month, index|
total += self.estimate_water[index].proposed_cost
end
end
return "$ "+number_with_precision(total, :precision => 2).to_s
end
不同的是调用了estimate_water的属性——在本例中为provided_cost,在其他情况下如成本、需求等。否则方法相同,但返回语句除外。
我想通过获取可枚举部分并将其拉入它自己的方法来干燥它:
def total_requested_attr(foo)
if self.estimate_water.count == 12
(1..12).each_with_index do |month, index|
total += self.estimate_water[index].foo
end
end
return total
end
'foo' 不会被评估为我传入的参数(假设我采用了早期的方法将字符串文字传递给此方法)。
我明白了:
undefined method `foo' for #<EstimateWater:0x007fa73da12570>
我希望 'foo' 是我传递的东西 - 所以如果我传递 'cost' 我希望语句执行就好像我在estimate_water 的实例上调用了成本一样。它没有。
我怎样才能通过发送不同的属性或其他方式使这个方法起作用?
【问题讨论】:
-
是
foo和对象还是字符串? -
你也不需要
self.。 -
只需使用'send'方法,如self.estimate_water[index].send(params)
-
@CarySwoveland 虽然正确,但我不喜欢省略“self”,因为代码读起来更含糊。包括 self 清楚地定义了下一个东西是 ActiveRecord 关系或实例方法,没有它,您可能正在对单独的实例变量进行操作,这会造成混乱而不是清晰。
标签: ruby-on-rails ruby ruby-on-rails-3 lambda proc