Adding a conversion method to a numeric value raises a SystemStackError

I am trying to add conversion methods to a numeric class, but when I run the following lines of code, I get a SystemStackError

puts 5.dollars.in(:euros)  # => 6.5
puts 1.dollar.in(:yen)

      

Here is my numeric class

class Numeric
  @@conversion_hash = {:dollar => {:yen => 0.013, :euros => 1.292, :rupees => 0.019}}

   def method_missing(method_id)
     name = method_id.to_s
     if name =~ /^dollar|yen|euros|rupee|$/
       self.send(name + 's')
     else
       super # pass the buck to superclass
     end
   end

   def dollars()
    puts "Called Dollars method"
    @current_currency = :dollar
    return self
   end

   def in(key)
     if @@conversion_hash.has_key?(@current_currency)
       puts "Current currency: #{@current_currency}"
       conversion_rate = @@conversion_hash[@current_currency]
       puts "Current conversion rate: #{conversion_rate}"
       if conversion_rate.has_key?(key)
         puts "we have that key"
         puts"What am I? #{self}"
         rate = conversion_rate[key]
         puts "Rate to multiply by #{rate}"
        return self.to_int * conversion_rate[key]
       end
     end
   end
 end

      

Any help is greatly appreciated.

+3


source to share


2 answers


You get infinite recursion in yours method_missing

because your regex is not quite correct. Try changing the line:

if name =~ /^dollar|yen|euros|rupee|$/

      

in



if name =~ /^dollar|yen|euros|rupee$/

      

This extra |

calls anything that matches the regular expression, so any other method recurses with an ever-expanding suffix s

.

In this case, it puts

looks like it seems to be trying to call to_ary

when trying to determine the type of its argument. I'm not entirely sure why this isn't just a use respond_to?

, though - it's deep inside the C elements, so I really don't know what's going on.

+3


source


Your decision is more complicated. - You don't need to change method_missing. Armando version works great. - You should just define dollar for the hash plus - find a way to call method_missing again from method in (this is your homework). The working solution only has 1 line of code + 2 lines of def surronding.



0


source







All Articles