Forum: Ruby Accessing variables/constants from another file

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Bf3ca289d85a0bf19705443afe9b412e?d=identicon&s=25 saudaziz@gmail.com (Guest)
on 2006-03-07 20:40
(Received via mailing list)
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.
1fba4539b6cafe2e60a2916fa184fc2f?d=identicon&s=25 unknown (Guest)
on 2006-03-07 21:48
(Received via mailing list)
Hi --

On Wed, 8 Mar 2006, saudaziz@gmail.com wrote:

> And another file driver.rb has following code
> 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 (dblack@wobblini.net)
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
This topic is locked and can not be replied to.