Class variables

S

Shuaib Zahda

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
 
S

Shuaib Zahda

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
 
7

7stud --

Shuaib said:
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
 

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

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top