【问题标题】:How can I pass an attribute as a param to a method which gets called on a class?如何将属性作为参数传递给在类上调用的方法?
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • .send()
猜你喜欢
  • 2021-02-05
  • 1970-01-01
  • 2010-11-13
  • 2019-07-30
  • 2011-08-15
  • 2020-07-03
  • 1970-01-01
  • 2014-03-22
  • 1970-01-01
相关资源
最近更新 更多