Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Strange things happening in my Int class
Index -> Programming, Ruby -> Ruby Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Clayton




PostPosted: 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.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...
Sponsor
Sponsor
Sponsor
sponsor
wtd




PostPosted: 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.

Now, with that out of the way...

You can rewrite this:

code:
puts "#{my_int.add(3,4,5)}"
puts "#{my_int.subtract(3,4,5)}"


Much more simply as:

code:
puts my_int.add(3, 4, 5)
puts my_int.subtract(3, 4, 5)
[Gandalf]




PostPosted: 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




PostPosted: 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.
Display posts from previous:   
   Index -> Programming, Ruby -> Ruby Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 4 Posts ]
Jump to:   


Style:  
Search: