Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created October 7, 2022 01:07
Show Gist options
  • Save havenwood/bee780f8db0a221cf5aace64a0178e6d to your computer and use it in GitHub Desktop.
Save havenwood/bee780f8db0a221cf5aace64a0178e6d to your computer and use it in GitHub Desktop.
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