Search code examples
rubymotion

Create a total of an array of numbers in RubyMotion


How would i create an array in RubyMotion and then display a total of every number in the array.

For example - Array[1..20] I want to display a total of 1+2+3+4+5+6....up to and including 20. So the total in this case would be 210.

I'm sure this is fairly straight forward but I am relatively new to RubyMotion and arrays bend my minuscule brain.

Cheers for any help


Solution

  • With a loop:

    numberArray = [1, 2, 3, 4]
    total = 0
    
    numberArray.each do |number|
     total += number
    end
    

    Where the += operator means:

    x += y
    

    is equal to

    x = x + y
    

    Edit :

    def getSum(my_array)
        total = 0
        my_array.each do |number|
            total += number
        end
        total
    end
    numberArr = [1,2,3,4]
    total = getSum(numberArr)
    label.text = "#{total}"
    

    I cannot test right now, but it should work.