Modules in Ruby

A

Abder-Rahman Ali

I have this script with slight change from "The Little Book Of Ruby":

http://pastie.org/private/6wgnmrtsodlmbh3ib1vg

If I type the following: puts MyModule.greet

I get the required result.

But, there is an instance method inside the module "greet". How can I
call that method at the time modules CANNOT be instantiated?

Thanks.
 
M

Martin DeMello

I have this script with slight change from "The Little Book Of Ruby":

http://pastie.org/private/6wgnmrtsodlmbh3ib1vg

If I type the following: puts MyModule.greet

I get the required result.

But, there is an instance method inside the module "greet". How can I
call that method at the time modules CANNOT be instantiated?

Include it in a class

class MyClass
include MyModule
end

a = MyClass.new
a.greet

martin
 
A

Abder-Rahman Ali

And, a small thing here. Can we say that "Modules" in Ruby are like
"Packages" in Java?

Thanks.
 
M

Martin DeMello

And, a small thing here. Can we say that "Modules" in Ruby are like
"Packages" in Java?

Modules in ruby serve a dual role as namespaces and mixins. You can
think of a mixin as a Java interface, but one that can have concrete
methods.

Check out the following:
http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html
http://adhirajrankhambe.wordpress.com/2009/01/04/a-word-about-modules-in-ruby/

and play with some code till it clicks. It's a very useful part of the language.

martin
 
A

Abder-Rahman Ali

A small thing here:

When I type:

puts MyModule::GOODMOODE

In the purpose of accessing a module's constant, I get the following:

uninitialized constant MyModule::GOODMOODE (NameError)

Although having the include.

How can I access a module's constant.

And, when reading about modules, the resources I saw so far mention that
modules includes:

1- Constants.
2- Methods.
3- Classes.

Don't they include variables?!

Thanks.
 
S

skim

[Note: parts of this message were removed to make it a legal post.]

In your private pastie, you have GOODMOOD, not GOODMOODE. I think this
could be why. Accessing MyModule::GOODMOOD worked.
 
A

Abder-Rahman Ali

Steve said:
In your private pastie, you have GOODMOOD, not GOODMOODE. I think this
could be why. Accessing MyModule::GOODMOOD worked.
Thanks everyone for your replies.
 

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,770
Messages
2,569,586
Members
45,084
Latest member
HansGeorgi

Latest Threads

Top