1
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.

maerics
  • 151,642
  • 46
  • 269
  • 291

1 Answers1

4

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
willglynn
  • 11,210
  • 48
  • 40
  • Thanks i get it what you explain but i didn't even get on thing. How method == :in is used. When you call 4.dollars.in(:yen) And also args.first how it works? – Shivam Chopra Oct 11 '12 at 21:50
  • method == :in ? :/ : :* Why this colon is used here? I don't know much about it if you can explain. Thanks a ton...!!! – Shivam Chopra Oct 11 '12 at 22:01
  • `send` takes a [symbol](http://www.randomhacks.net/articles/2007/01/20/13-ways-of-looking-at-a-ruby-symbol) to indicate which method it should invoke. The ternary operator returns either `:/` (division) or `:*` (multiplication). Thus, the `send` call boils down to `self / ...` or `self * ...`. – willglynn Oct 11 '12 at 22:03