困惑?
我有 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 的属性 - 在本例中为 proposed_cost,在其他情况下为 cost、need 等。除 return 语句外,其他方法相同。
我想通过获取可枚举部分并将其拉入它自己的方法来解决这个问题:
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 实例上调用 cost 一样执行。它没有。
如何通过发送不同的属性或其他方式使该方法起作用?
最佳答案
您没有真正指定 foo 是什么,所以我只能假设它是一个属性或方法名称。
您可以使用 Object#send
来实现它像这样的功能:
def total_requested_attr(foo)
if self.estimate_water.count == 12
(1..12).each_with_index do |month, index|
total += self.estimate_water[index].send(foo)
end
end
return total
end
由于您的特定于某些我无法轻松展示的用例,因此我制作了一个示例向您展示:
class Say
def hello(param)
puts "hello".send(param)
end
end
prm = "to_i"
Say.new.hello(prm)
这实际上等同于 "hello".to_i
并输出 0
。
关于ruby-on-rails - 如何将属性作为参数传递给在类上调用的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28550717/