Created
August 2, 2012 02:27
-
-
Save ephekt/3232629 to your computer and use it in GitHub Desktop.
array iteration problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def add1(arr, val, n) | |
# how many times are we going to increment | |
increment_count = n == 0 ? arr.length : n.abs | |
# are we going up or down the array | |
indices = n < 0 ? (-1..-arr.length) : (0...arr.length) | |
# iterate and update the array in place | |
indices.each do |index| | |
if (arr_value = arr[index]) == val | |
arr[index] = arr_value + 1 | |
# decrement and check the count all in one go | |
break if (increment_count -= 1) == 0 | |
end | |
end | |
# nothing to return since the array is updated in place | |
end |
Woops - try it now. Removed the then and turend the breaker into one line
and you need to return the array at the end of the method
def add1(arr, val, n)
increment_count = n == 0 ? arr.length : n.abs
indices = n < 0 ? (-1..-arr.length) : (0...arr.length)
indices.each do |index|
arr[index] = arr[index] + 1 if val == arr[index]
break if (increment_count -= 1) == 0
end
arr
end
Yes, to be a true rubyist one would need to do that. Because modifications are in place, one could also just add ! to the method definition.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you get an undefined
arr_value
in this