2012-08-02 55 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