Skip to content

Instantly share code, notes, and snippets.

@mboeh
Created August 2, 2012 00:32
Show Gist options
  • Save mboeh/3231908 to your computer and use it in GitHub Desktop.
Save mboeh/3231908 to your computer and use it in GitHub Desktop.
add1
# http://blog.jazzychad.net/2012/08/01/array-iteration-problem.html
def add1(arr, val, n)
range = (0 ... arr.length)
indexes = n < 0 ? range.reverse_each : range.each
n = n.zero? ? arr.length : n.abs
indexes.each do |idx|
if arr[idx] == val
arr[idx] += 1
(n -= 1).zero? and break
end
end
arr
end
if $0 == __FILE__
def assert(a) a or fail "failed assertion" end
assert add1([1,4,1,5,1], 1, 0) == [2,4,2,5,2]
assert add1([1,4,1,5,1], 1, 2) == [2,4,2,5,1]
assert add1([1,4,1,5,1], 1, -2) == [1,4,2,5,2]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment