2015-12-02 71 views
1

我有2个ruby文件,Demo.rb和Config.rb。Ruby中的模块和类

在我Demo.rb文件,我需要我的Config.rb文件:

require './Config' 

puts Config::test 
puts Config::test2 

Config.rb如下:

module Config 
    # trying to add varibles/config details 
    config1 = 'test' 
    config2 = 'test2' 
end 

现在我想要做的是在我的Config模块中有一些变量,然后能够从Demo.rb中读取这些值,但是我不断收到错误。我试过Config.test为好,但它一直在抱怨:

undefined method `user' for Config:Module 

我读到这里:http://learnrubythehardway.org/book/ex40.html这件事,但我似乎做什么,它的要求。不知道我哪里错了。

+0

错误消息似乎并不符合你的代码已经发布 –

+0

我已经修复它,我正在通过不同的名称。对于那个很抱歉。 – jackfrost5234

回答

2

这只适用于常量。在Ruby中,常量开始以大写字母:

module Config 
    # trying to add varibles/config details 
    Config1 = 'test' 
    Config2 = 'test2' 
end 

puts Config::Config1 
# => test 

你也可以定义一个模块方法:

module Config 
    def self.config1 
    'test' 
    end 
end 

puts Config.config1 
# => test