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

How can I pass an attribute as a param to a method which gets called on a class?

困惑?

我有 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 的实例上调用成本一样执行。它没有。

如何通过发送不同的属性或其他方式使此方法起作用?

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