模块和Ruby中的类

时间:2015-12-02 21:53:25

标签: ruby

我有2个ruby文件,Demo.rb和Config.rb。

在我的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关于它,但我似乎正在做它所要求的事情。不知道我哪里出错了。

1 个答案:

答案 0 :(得分: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
相关问题