Search code examples
rubyeclipseruby-2.0dltk

Understanding ruby modules


I am new to Ruby, using eclipse, DLTK ruby plugin and Ruby 2.0. I created an Ruby module file called AModule.rb which has the code:

module AModule
  aConstant = 7
end

This is called from a test ruby script in the same project:

require 'AModule'
puts AModule::aConstant

In the second line of the above code, i get the error in '<main>': undefined local variable or method 'aModule' for main:Object (NameError)

I followed my codeacademy tutorial, so I did not expect this to happen. What is the mistake that I am making here ?

PS: Actually, I wanted to name my module file **aM**odule.rb and not **AM**odule.rb . But, the DLTK plugin quietly makes the first alphabet uppercase. Could this be a bug ?


Solution

  • Your problem is that name of constant must start with UpperCaseLetter. Otherwise Ruby will think of it as of local variable. So what's wrong with it? Short answer: it's all about scope. Local variables are only visible in their lexical scope. Constant is a quite different thing. Constant can always be accessed via so called namespace-resolution operator (::).

    Read more info about Ruby scoping here.