How to include a class and create an object?

Hi

I have a file in /lib/test_class.rb whic looks like this

module TestClass
class TestClass

 def mehtod1
 end

 def more methods ....

end

end

in one of my controllers I have

require ‘test_class’

This seems to work, however when I do the next line to create an object
it fails

test = TestClass.new

Any ideas where I am going wrong?

Uh, you have to specify the module name…

test = TestClass::TestClass.new

Ruby may be smart, but it’s not prescient.

Jason

Jason R. wrote:

Uh, you have to specify the module name…

test = TestClass::TestClass.new

Ruby may be smart, but it’s not prescient.

Jason

Exactly.

Remember that when you say:

TestClass.new

you are actually calling the “new” method on the module, not the class.
To actually get the class you have to dig into it with the “::”
operator.

TestClass::TestClass.new

However, if you simply want to inlcude the class in your app you dont
need to wrap it in a module at all. And then you dont need the :: at
all.

Alex W. wrote:

you are actually calling the “new” method on the module, not the class.
To actually get the class you have to dig into it with the “::”
operator.

TestClass::TestClass.new

cool thanks, whats the advantage of wrapping the code in a module, i’ve
always done it, but not sure why?

one last thing

How can I call a function on that class

if I have created an object
pTest = TestClass::TestClass.new

Should I not be able to do this, if there is a method inside the class
called test?

pTest.test

if getting the error (private method `test’ called)

Please read this:

http://www.rubycentral.com/book/

Jason

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs