Created
July 14, 2017 05:54
-
-
Save MuffinTheMan/ab2b25bdc64bc458ee91fbe352332600 to your computer and use it in GitHub Desktop.
Ruby monkey patch for a version of Array#delete_at that returns the array with the element at the given index removed rather than returning the removed element
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
class Array | |
def remove_at(i) | |
# handle index out of bounds by returning unchanged array | |
return self if i >= self.length | |
# remove the i-th element from the end if i is negative | |
if i < 0 | |
i += self.length | |
# handle index out of bounds by returning unchanged array | |
return self if i < 0 | |
end | |
# Return an array composed of the elements before the specified | |
# index plus the elements after the specified index | |
return self.first(i) + self.last(self.length - i - 1) | |
end | |
end | |
test = [0,1,2,3,4,5] | |
puts test.remove_at(3).inspect | |
puts test.remove_at(5).inspect | |
puts test.remove_at(6).inspect | |
puts test.remove_at(-7).inspect | |
puts test.remove_at(-2).inspect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment