Last active
June 3, 2018 09:52
-
-
Save nwtgck/0307ec0aad17b7fddf83c114215f69c1 to your computer and use it in GitHub Desktop.
This file contains 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
# (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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It may be useful to debug index problem.