ruby - Program Freeze: Adding Array Elements -
i have solution, not 1 want. here's code:
def sum(nums) idx = 0 while idx < nums.length nums[idx] = idx * nums[idx] idx += 1 end print nums idx2 = 0 idx3 = idx2 + 1 while idx3 < nums.length result = (nums[idx2].to_i) + (nums[idx3].to_i) idx2 += 1 end puts result end sum([2,3]) sum([2,3,5]) sum([2,3,5,2]) two things don't understand happening @ sec while loop. first, if utilize while idx2 < nums.length unusual add-on (the array sums come 6, 13, 9). if utilize while idx3 < nums.length programme not run way through. stops @ line 14 (at 2nd loop), must interupt ctrl+c.
i'm sure i'm not understanding what's going on here i'm asking help.
i realize can utilize inject , each loops simpler sum solution (and map , procs/blocks , other objects). i'm trying understand how these things work, not come solution.
idx3 < nums.length
will true because aren't changing neither of values, right remain bigger left , loop never ends.
using other status instead, result in cannot predict without knowing nums is, not expect since you're overwriting value had stored on result, lastly iteration create noticeable.
there no array sums can see here :s
i suggest seek programme , test 1 concept @ time. if test of them @ 1 time won't know causing what.
ruby arrays
No comments:
Post a Comment