Skip to content

Instantly share code, notes, and snippets.

@ephekt
Created August 2, 2012 02:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ephekt/3232629 to your computer and use it in GitHub Desktop.
Save ephekt/3232629 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|
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
@jhsu
Copy link

jhsu commented Aug 3, 2012

you get an undefined arr_value in this

@ephekt
Copy link
Author

ephekt commented Aug 3, 2012

Woops - try it now. Removed the then and turend the breaker into one line

@jhsu
Copy link

jhsu commented Aug 3, 2012

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

@ephekt
Copy link
Author

ephekt commented Aug 3, 2012

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