2011-03-24 191 views
17

我有一个常量的红宝石模块。它有一个变量列表和一个应用格式化的方法。 我似乎无法访问此模块中的方法。任何想法为什么?红宝石模块方法访问

+9

你可以发布你的代码吗? – 2011-03-24 09:45:12

回答

51

如果include模块的方法成为一种实例方法,但如果你extend模块,然后就变成了类方法

module Const 
    def format 
    puts 'Done!' 
    end 
end 

class Car 
    include Const 
end 

Car.new.format # Done! 
Car.format # NoMethodError: undefined method format for Car:Class 

class Bus 
    extend Const 
end 

Bus.format # Done! 
Bus.new.format # NoMethodError: undefined method format 
+1

这真的很有帮助。谢谢:) – Rads 2013-11-21 07:19:36

0

一般而言,模块,这些东西应该发生:

- 在application.rb中>自动加载路径,添加行:

config.autoload_paths += %W(#{config.root}/lib) 

- 位于/ lib

>放置模块

- >包含模块'包含NAMEOFMODULE'

(如果模块具有类似下划线game_engine,你需要'包含GameEngine')

+0

我不能访问同一模块内的方法: – 2011-03-24 10:12:04

+0

像这个模块的东西常量 #要更改此模板使用文件|设置|文件模板。 高清remove_formatting(原件) 转换= original.replace(original.gsub!(/ \ w + /, '')) 回报转换 结束 名称= “这是一个名为” 结束 – 2011-03-24 10:13:15

25
module Foo 
    def self.hello # This is a class method 
    puts "self.hello" 
    end 

    def hello # When you include this module, it becomes an instance method 
    puts "hello" 
    end 
end 

Foo.hello #=> self.hello 

class Bar 
    include Foo 
end 

Bar.new.hello #=> hello 
+1

,如果你有什么在Foo中有其他方法,并且您想在该方法中访问hello?你会怎么做? – 2011-03-24 10:18:09

+0

我不明白。你可以在该方法中调用'hello'。 – GutenYe 2011-07-04 06:37:28

+0

简单但完整的答案。 – Hito 2015-04-24 21:54:16