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  # => 6.5


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')
       super # pass the buck to superclass

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

   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]


Any help is greatly appreciated.


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|$/



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.



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.



All Articles