ruby - 将转换方法添加到 Numeric 导致 SystemStackError

标签 ruby

我正在尝试向 Numeric 类添加转换方法,但是当我运行以下代码行时,我得到了 SystemStackError

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

这是我的数字类

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

非常感谢任何帮助。

最佳答案

您在 method_missing 中得到无限递归,因为您的正则表达式不太正确。尝试更改行:

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

到:

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

那个额外的 | 导致任何东西都匹配正则表达式,因此任何其他方法都在不断扩展 s 的后缀。

在这种情况下,当 puts 试图确定其参数的类型时,它似乎试图调用 to_ary。我不太确定为什么它不只是使用 respond_to? 虽然它在 C 内部很深,所以我真的不知道发生了什么。

关于ruby - 将转换方法添加到 Numeric 导致 SystemStackError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9625661/

相关文章:

python - Python "_"的 Ruby 等价物

ruby-on-rails - Rails 4 date_field,最小和最大年份?

ruby /Rspec : Possible to compare the content of two objects?

ruby-on-rails - Ruby on Rails 迁移——创建新的数据库架构

ruby - 如何访问 ruby​​ 中闭包中的外部变量?

ruby - 如何在 Ruby 正则表达式中匹配韩文字符?

ruby-on-rails - 更改 bundle 安装 Ruby 版本

mysql - 通过父子关联将数据从一个表迁移到另一个表

ruby - Rails 获取没有日期的当前时间

ruby - 无法在 mac 上为 ruby​​ 安装 Mechanize