-
-
Save havenwood/bee780f8db0a221cf5aace64a0178e6d 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
module NilArray | |
refine Array do | |
def fetch(index, ...) | |
return if index.negative? | |
super | |
end | |
def [](left, right = nil) | |
if left.is_a?(Range) | |
return if left.begin&.negative? || left.end&.negative? | |
else | |
return if left.negative? || right&.negative? | |
end | |
super | |
end | |
end | |
end | |
using NilArray | |
numbers = [*42..50] | |
p numbers[-1] | |
p numbers[-3..-1] | |
p numbers[..-1] | |
p numbers.fetch(-1) | |
p numbers.fetch(-1) { rand } | |
p numbers.fetch(-1, 42) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment