2012-08-02 58 views
1

我下:Rails的添加方法Ruby类问题

ruby-1.9.3-p194 
Rails 3.0.9 

我想在我的观点方法与数字数据类型使用percent_of。例如,<%= 10.persent_of(50) %>它等于20%

这样做,我已经创建lib/numeric.rb文件,其中包含

class Numeric 
    def percent_of(n) 
    self.to_f/n.to_f * 100.0 
    end 
end 

但我得到了一个错误:

undefined method `percent_of' for 10:Fixnum 

我尝试添加定义require 'Numeric'但它并没有帮助我。

帮我看看。

+0

你重新启动服务器? – az7ar 2012-08-02 08:58:44

+2

你可能想把你的文件放在'config/initializers'中。这样你就不需要它了。 – Mischa 2012-08-02 09:03:04

+0

感谢您的建议。 – 2012-08-02 14:09:41

回答

1

改为尝试require 'numeric'。你需要的是文件,而不是课程。

+0

非常感谢,它的工作原理 – 2012-08-02 09:10:19

1

检查您的application.rb文件中是否有config.autoload_paths += %W(#{config.root}/lib)。您应该延长Fixnum对象,而不是数字:

class Fixnum 
    def percent_of(n) 
    self.to_f/n.to_f * 100.0 
    end 
end 

然后要求或包括这application_helper.rb,使其适用于所有的意见:

require 'numeric'include Numeric