问题更新
这是我根据一些研究和发现所做的。
第 1 步 - 我的 Rails 3 项目中有这个模块,并将其放在我的 lib 文件夹中
# lib/enumerable.rb
module Enumerable
def sum
return self.inject(0){|acc,i|acc +i}
end
def average
return self.sum/self.length.to_f
end
def sample_variance
avg=self.average
sum=self.inject(0){|acc,i|acc +(i-avg)**2}
return(1/self.length.to_f*sum)
end
def standard_deviation
return Math.sqrt(self.sample_variance)
end
end
第 2 步 - 根据此 blog article ,在 Rails 3 中,您的 lib 文件夹不会自动加载。为了加载此模块,您需要转到 config/application.rb
并输入:
config.autoload_paths += %W(#{config.root}/lib)
第 3 步 - 然后在您的模型中,我的理解是您输入此内容以获取模块。
class MyModel < ActiveRecord::Base
include Enumerable
end
第 4 步 - 然后我尝试重新启动 Rails 服务器并尝试这个,当我期望它为真时我得到了假。
MyModel.respond_to?('sample_variance')
# false, when it should be true
我做错了什么?我不该说实话吗?
最佳答案
你包含的主要 Enumerable 模块(不是你的扩展)无疑是有效的,你可以通过简单地检查任何混合的方法来测试它。问题是,你的“Include Enumerable”可能没有包含你的文件,而是主模块。
一个建议是重命名扩展的文件名,并通过带有
的初始化程序加载它require 'my_enumerable.rb'
这样你肯定会同时加载 Enumerable 和你对 Enumerable 的扩展。
关于ruby - 在 Rails 3 中扩展 Enumerable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5280640/