【问题标题】:Can anyone explain this Ternary and the method_missing part of the code?谁能解释这个三元和代码的method_missing部分?
【发布时间】:2012-10-02 15:57:36
【问题描述】:
class Numeric
  @@currencies = {'yen' => 0.013, 'euro' => 1.292, 'rupee' => 0.019, 'dollar' => 1.0}

  def method_missing(method, *args)
    singular_currency = (method == :in ? args.first : method).to_s.gsub(/s$/, '')
    if @@currencies.has_key?(singular_currency)
      self.send(method == :in ? :/ : :*, @@currencies[singular_currency])
    else
      super
    end
  end
end

我没有得到确切的代码,我知道,它是用于转换的,但我没有得到三元运算符部分。

【问题讨论】:

    标签: ruby ternary-operator method-missing


    【解决方案1】:

    这些行:

    singular_currency = (method == :in ? args.first : method).to_s.gsub(/s$/, '')
    self.send(method == :in ? :/ : :*, @@currencies[singular_currency])
    

    ...也可以写成:

    if method == :in
      singular_currency = args.first.to_s.gsub(/s$/, '')
      self / @@currencies[singular_currency]
    else
      singular_currency = method.to_s.gsub(/s$/, '')
      self * @@currencies[singular_currency]
    end
    

    这样写更清楚,但增加了更多重复。在 Ruby(以及整个 Smalltalk 系列)中,方法调用和消息发送是一回事。 send 是调用其参数中指定的方法的方法。

    将此添加到 method_missing 可以让您支持如下语法:

    4.dollars
    # => 4 * 1.0
    4.dollars.in(:yen)
    # => 4 * 1.0 / 0.013
    
    4.yen
    # => 4 * 0.013
    4.yen.in(:dollars)
    # => 4 * 0.013 / 1.0
    

    【讨论】:

    • 谢谢你的解释我明白了,但我什至没有理解。如何使用方法 == :in。当你调用 4.dollars.in(:yen) 还有 args.first 它是如何工作的?
    • 方法 == :in ? :/ : :* 为什么这里使用这个冒号?如果您能解释一下,我对此了解不多。非常感谢...!!!
    • send 采用symbol 来指示它应该调用哪个方法。三元运算符返回:/(除法)或:*(乘法)。因此,send 调用归结为self / ...self * ...
    猜你喜欢
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 2017-04-22
    • 2011-02-11
    相关资源
    最近更新 更多