# Class variables

**URL:** <https://www.ruby-forum.com/t/class-variables/117894>\
**Category:** Ruby\
**Created:** [October 22, 2007, 6:53am UTC](https://www.ruby-forum.com/t/class-variables/117894 "2007-10-22T06:53:49Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![shuaib85](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/bbce88/32.png) [@shuaib85](https://www.ruby-forum.com/u/shuaib85)\
**Post date:** [October 22, 2007, 6:53am UTC](https://www.ruby-forum.com/t/class-variables/117894/1 "2007-10-22T06:53:49Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![shuaib85](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/bbce88/32.png) [@shuaib85](https://www.ruby-forum.com/u/shuaib85)\
**Post date:** [October 22, 2007, 7:12am UTC](https://www.ruby-forum.com/t/class-variables/117894/2 "2007-10-22T07:12:12Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![shuaib85](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/bbce88/32.png) [@shuaib85](https://www.ruby-forum.com/u/shuaib85)\
**Post date:** [October 22, 2007, 7:17am UTC](https://www.ruby-forum.com/t/class-variables/117894/3 "2007-10-22T07:17:11Z")

</div>

Shuaib Z. 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
