
-----------------------------------
Clayton
Fri Nov 03, 2006 9:37 pm

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.


class Int
    def initialize(num)
        @@val = num
    end
    def add(*ints)
        ints.each do |element|
            @@val += element
        end
    end
    def subtract(*ints)
        ints.each do |element|
            @@val -= element
        end
    end
end

my_int = Int.new(6)
puts "#{my_int.add(3,4,5)}"
puts "#{my_int.subtract(3,4,5)}"


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...

-----------------------------------
wtd
Fri Nov 03, 2006 10:56 pm


-----------------------------------
Well, one thing...

An @@ prefix indicates a class variable, rather than an instance variable.  

Now, with that out of the way...

You can rewrite this:

puts "#{my_int.add(3,4,5)}"
puts "#{my_int.subtract(3,4,5)}"

Much more simply as:

puts my_int.add(3, 4, 5)
puts my_int.subtract(3, 4, 5)

-----------------------------------
[Gandalf]
Sat Nov 04, 2006 11:06 pm

Re: Strange things happening in my Int class
-----------------------------------
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
Sun Nov 05, 2006 8:27 am

Re: Strange things happening in my Int class
-----------------------------------
"]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.
