Skip to content

Instantly share code, notes, and snippets.

@jhsu
Forked from ephekt/rb_array_iterate.rb
Created August 3, 2012 04:47
Show Gist options
  • Save jhsu/3244473 to your computer and use it in GitHub Desktop.
Save jhsu/3244473 to your computer and use it in GitHub Desktop.
array iteration problem
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|
arr[index] = arr[index] + 1 if val == arr[index]
break if (increment_count -= 1) == 0
end
arr
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment