Accessing variables/constants from another file

S

saudaziz

How can i access "myvariable" in the provided code from

Say constants.rb has the following code

Module

myvariable = 'foo'

end

And another file driver.rb has following code

require constants

class myclass < food

def busted
#how can i call 'myvariable' constant here?

end

end


Also, if you can tell me what exactly is the difference between require
and include, that would be great help. I don't see any clear
explanation anywhere for the above.
 
D

dblack

Hi --

How can i access "myvariable" in the provided code from

Say constants.rb has the following code

Module

myvariable = 'foo'

end

And another file driver.rb has following code

require constants

class myclass < food

def busted
#how can i call 'myvariable' constant here?

end

end

The whole idea of "local" variables is to be local :) If you want
something to be visible between files, you should make it a constant
or a method:

# constants.rb:

module M
def M.my_value
"foo"
end
end

# driver.rb:

require 'constants'

class MyClass < Food
def not_busted
myvariable = M.myvalue
# etc.
end
end


or something like that.
Also, if you can tell me what exactly is the difference between require
and include, that would be great help. I don't see any clear
explanation anywhere for the above.

"require" reads in a file (either a Ruby file or a compiled file for a
C extension). "include" mixes a module into a class or into another
module. So the usual sequence is require, then include: first you
read in the file that defines a module (like M in my example), then
you do something with the module (in my example I just used a method
in it, but you can also "include" modules).


David

--
David A. Black ([email protected])
Ruby Power and Light, LLC (http://www.rubypowerandlight.com)

"Ruby for Rails" chapters now available
from Manning Early Access Program! http://www.manning.com/books/black
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top