beginning question. modules + object creation

C

Corey Konrad

I was wondering if i create a modules file called mathematics.rb:

module Mathematics
class Add
def add(operand_one, operand_two)
return operand_one + operand_two
end

end#end class
end

and then i create another file called usemodules.rb

require 'mathematics'


adder = Add.new
puts "2 + 3 = " + adder.add(2, 3).to_s

how do i create an Add object in this new file, i understand i could
just make the add method above into a class method and then i wouldnt
need to create an object at all. However how would i create an object to
use.

thanks
 
C

Corey Konrad

Corey said:
I was wondering if i create a modules file called mathematics.rb:

module Mathematics
class Add
def add(operand_one, operand_two)
return operand_one + operand_two
end

end#end class
end

and then i create another file called usemodules.rb

require 'mathematics'


adder = Add.new
puts "2 + 3 = " + adder.add(2, 3).to_s

how do i create an Add object in this new file, i understand i could
just make the add method above into a class method and then i wouldnt
need to create an object at all. However how would i create an object to
use.

thanks

never mind i figured it out on my own i would do it like
Mathematics::Add.new
zen and the art of programming as soon as i shut my brain off by asking
a question the answer pops in my head, lol.
 
G

Gary Wright

I was wondering if i create a modules file called mathematics.rb:

module Mathematics
class Add
def add(operand_one, operand_two)
return operand_one + operand_two
end

end#end class
end

and then i create another file called usemodules.rb

require 'mathematics'


adder = Add.new
puts "2 + 3 = " + adder.add(2, 3).to_s

Because you nested your class Add within Mathematics you have to
use the fully qualified name when you are writing code that
is outside the Mathematics module:

adder = Mathematics::Add.new
puts "2 + 3 = #{adder.add(2,3)}"

Gary Wright
 

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
474,238
Messages
2,571,192
Members
47,829
Latest member
wyattmoon

Latest Threads

Top