Global constants

K

Kless

I want set up some constants that can be accesed since another
classes.

Which is the best way? Using a singleton to access to variables? (as
if were global vars.)?
 
M

Michael Morin

Kless said:
I want set up some constants that can be accesed since another
classes.

Which is the best way? Using a singleton to access to variables? (as
if were global vars.)?

You can use a module for this. The classes don't necessarily have to be
in the module either, if outside the module they can address the
constant as MyModule::CONSTANT or the classes can include MyModule if it
makes sense to do so.

module MyModule
CONSTANT = "test"

class MyClass1
def print_test
puts CONSTANT
end
end

class MyClass2
def say_something
puts CONSTANT
end
end
end

MyModule::MyClass1.new.print_test
MyModule::MyClass2.new.say_something

--
Michael Morin
Guide to Ruby
http://ruby.about.com/
Become an About.com Guide: beaguide.about.com
About.com is part of the New York Times Company
 
K

Kless

Thank you for your help and the fast reply.

I come from Python, a great language, but I'm loving Ruby.
 

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

Forum statistics

Threads
473,771
Messages
2,569,587
Members
45,099
Latest member
AmbrosePri
Top