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

Username:   Password: 
 RegisterRegister   
 Array trouble
Index -> Programming, Ruby -> Ruby Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Clayton




PostPosted: Fri Oct 27, 2006 7:26 pm   Post subject: Array trouble

i have a function called add, and from wtd's tutorial, it should be able to take any number of integers and form them into an array, however, it doesnt seem to be working right. my code:

Ruby:

def add(*integers)
        total = 0
        integers.each do |array_element|
                total += integers(array_element)
        end
        return total
end

puts "#{add(1,2,3,4,5,6,7,8,9)}"


I keep getting an error on line 3 and I don't know why (I think it has something to do with "integers" but i dont know for sure.)
Sponsor
Sponsor
Sponsor
sponsor
wtd




PostPosted: Fri Oct 27, 2006 9:55 pm   Post subject: (No subject)

In your function, "integers" is an Array.

When you use "each" it passes each element of the Array to the block in turn.

code:
def sum(*integers)
   total = 0
   integers.each { |integer| total += integer }
   total
end


But then, you really should...

code:
class Array
   def sum
      inject(0) { |a, b| a + b }
   end
end


code:
[1, 2, 3, 4].sum # => 10
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  [ 2 Posts ]
Jump to:   


Style:  
Search: