Skip to content

Instantly share code, notes, and snippets.

@nwtgck
Last active June 3, 2018 09:52
Show Gist options
  • Save nwtgck/0307ec0aad17b7fddf83c114215f69c1 to your computer and use it in GitHub Desktop.
Save nwtgck/0307ec0aad17b7fddf83c114215f69c1 to your computer and use it in GitHub Desktop.
# (from: http://melborne.github.io/2013/08/30/monkey-patching-for-prudent-rubyists/)
class Array
alias :get_at :[]
private :get_at
alias :set_at :[]=
private :set_at
def in_bound?(idx)
0 <= idx && idx < self.size
end
# NOTE: Overwrite
def [](idx)
if self.in_bound?(idx)
get_at(idx)
else
raise IndexError.new("index #{idx} outside of array bounds: 0...#{self.size}")
end
end
# NOTE: Overwrite
def []=(idx, val)
if self.in_bound?(idx)
set_at(idx, val)
else
raise IndexError.new("index #{idx} outside of array bounds: 0...#{self.size}")
end
end
end
if __FILE__ == $0
begin
p([1, 2, 3][10])
rescue
puts("Should be printed!")
end
arr = [1, 2, 3]
arr[0] = 10
p(arr)
end
@nwtgck
Copy link
Author

nwtgck commented Jun 3, 2018

It may be useful to debug index problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment