当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby - Can anyone explain this Ternary and the method_missing part of the code?

问题描述:

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

I didn't get the code exactly, I know, it's for the conversion but I'm not getting the ternary operator part.

网友答案:

These lines:

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

...could also be written:

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

Writing it that way is more clear, but adds more duplication. In Ruby (and the entire Smalltalk family), method calls and message sends are the same thing. send is a method that calls a method specified in its parameters.

Adding this to method_missing lets you support a syntax like:

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
分享给朋友:
您可能感兴趣的文章:
随机阅读: