jackfrost5234
jackfrost5234

Reputation: 229

Modules & Classes in Ruby

I have 2 ruby files, Demo.rb and Config.rb.

In my Demo.rb file I'm requiring my Config.rb file:

require './Config' 

puts Config::test
puts Config::test2

Config.rb is as follows:

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

Now what I'm trying to do is have some variables in my Config module, and then be able to read those values from Demo.rb, but I keep getting an error. I've tried Config.test as well, but it keeps complaining about:

undefined method `user' for Config:Module

I was reading here: http://learnrubythehardway.org/book/ex40.html about it, but I seem to be doing what it's asking. Not sure where I'm going wrong.

Upvotes: 1

Views: 74

Answers (1)

Jordan Running
Jordan Running

Reputation: 106127

This only works for constants. In Ruby, constants start with a capital letter:

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

puts Config::Config1
# => test

You could also define a module method:

module Config
  def self.config1
    'test'
  end
end

puts Config.config1
# => test

Upvotes: 2

Related Questions