Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding conversion method to Numeric causes SystemStackError

Tags:

ruby

I'm attempting to add conversion methods to the 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.

like image 777
aahrens Avatar asked Dec 01 '25 06:12

aahrens


1 Answers

You're getting infinite recursion in your method_missing because your regex isn't quite right. Try changing the line:

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

to:

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

That extra | is causing anything to match the regex, so any other method is recursing with a continually extending suffix of s.

In this case it looks like puts seems to be trying to call to_ary when it's trying to determine the type its argument. I'm not exactly sure why it's not just using respond_to? though - it's deep in the C internals so I don't really know what's happening.

like image 141
matt Avatar answered Dec 05 '25 01:12

matt