Newbie question

Learning about classes in Ruby. The following very simple class returns
an error (in <top (required)>': undefined methodsum’ for Input1:Class
(NoMethodError)
from -e:1:in load' from -e:1:in')

What am I doing wrong?

class Input1

def initialize(n1, n2)
@n1 = n1
@n2 = n2
end

def sum
@n1 + @n2
end

end

puts "Enter first number: "
@n1 = gets
puts "Enter second number: "
@n2 = gets
puts Input1.sum.to_s

The defs you created inside your class cannot be called on the class
itself. You have to create on object of the class and call the methods
on the object:

my_input = Input1.new(10, 20)

You should also be aware that the variables @n1 and @n2 that you used
outside the class are different variables than the ones inside the
class.

Also, the way you have written your class, there is no way for you to
read
or set the variables @n1 and @n2 for the object you created once those
values have been initialized.

7stud – wrote in post #1147486:

The defs you created inside your class cannot be called on the class
itself. You have to create on object of the class and call the methods
on the object:

my_input = Input1.new(10, 20)

You should also be aware that the variables @n1 and @n2 that you used
outside the class are different variables than the ones inside the
class.

Also, the way you have written your class, there is no way for you to
read
or set the variables @n1 and @n2 for the object you created once those
values have been initialized.

Thanks for the response. After trying quite a bit, I’m still at a loss.
What I originally did was to write a script version of this class (that
worked pretty well) and turn it into an O-O version (i.e., a class),
which doesn’t work. It does work with other similar exercises that don’t
use keyboard input, but as soon as keyboard input is involved, it
breaks.

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