如何将属性作为参数传递给在类上调用的方法?

时间:2015-02-16 21:32:32

标签: ruby-on-rails ruby ruby-on-rails-3 lambda proc

混淆?

我有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,在其他情况下是诸如成本,需要等等。否则方法是相同的,除了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。它没有。

如何通过发送不同的属性或其他方法使此方法有效?

1 个答案:

答案 0 :(得分:3)

你没有真正指定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