Class variables

I have tried to deal with class variables but I received weird output
the code is here and below it is the output

class ClassVariable
attr_accessor :total
@@num1 = 0
@@num2 = 0

def getValues
puts "enter a number"
@@num1 = gets
puts "enter a number"
@@num2 = gets
end

def sum
@@num1 + @@num2
end

end

obj = ClassVariable.new
obj.getValues
puts obj.sum

-- output
enter a number
4
enter a number
5
4
5

as u can see in the output it just repeats them and did not sum them up
and returns the summation value.
any idea?
Regards
Shuaib

···

--
Posted via http://www.ruby-forum.com/.

Sorry guys
after a more search effort i figured it out.
i forgot to call to_i method

so
def sum
@@num1.to_i + @@num2.to_i
end

and it works
the reason is that @@num1 ans @@num2 are string.

Sorry again

···

--
Posted via http://www.ruby-forum.com/.

Shuaib Zahda wrote:

I have tried to deal with class variables but I received weird output
the code is here and below it is the output

as u can see in the output it just repeats them and did not sum them up
and returns the summation value.
any idea?

Your problem has nothing to do with class variables. The gets() method
returns a *string* not a number. When the user enters some characters
and then hits return, gets() will return something like this:

10\n

The '\n' is the newline character that was entered when the return key
was pressed. The second string will look something like:

20\n

When you add those strings together, you get:

"10\n20\n"

Then when you use puts to output the string, your computer screen
converts the '\n' characters to newlines, which produces:

10
20

···

--
Posted via http://www.ruby-forum.com/\.