Posted: Fri Nov 03, 2006 9:37 pm Post subject: Strange things happening in my Int class
okay, I've gotten into class writing, and I'm taking an Int class that I wrote in Turing, and I am trying to convert it over to Ruby (I know it's reinventing the wheel, but I'm doing it just because), and some weird things are going on.
Ruby:
class Int
def initialize(num)
@@val = num
end def add(*ints)
ints.eachdo |element|
@@val += element
end end def subtract(*ints)
ints.eachdo |element|
@@val -= element
end end
end
could someone please tell me why the code above would return 345 when the call to my_int.add(3,4,5) is made? It doesn't make sense why this is happening...
Sponsor Sponsor
wtd
Posted: Fri Nov 03, 2006 10:56 pm Post subject: (No subject)
Well, one thing...
An @@ prefix indicates a class variable, rather than an instance variable.
Posted: Sat Nov 04, 2006 11:06 pm Post subject: Re: Strange things happening in my Int class
Freakman wrote:
could someone please tell me why the code above would return 345 when the call to my_int.add(3,4,5) is made? It doesn't make sense why this is happening...
Sure it makes sense. How would " " + 3 + 4 + 5 look? Since concatenation and addition have the same precedence, it would become " 345".
wtd
Posted: Sun Nov 05, 2006 8:27 am Post subject: Re: Strange things happening in my Int class
[Gandalf] wrote:
Freakman wrote:
could someone please tell me why the code above would return 345 when the call to my_int.add(3,4,5) is made? It doesn't make sense why this is happening...
Sure it makes sense. How would " " + 3 + 4 + 5 look? Since concatenation and addition have the same precedence, it would become " 345".
Ruby is strongly typed, so this doesn't work at all.