Last active
January 5, 2022 20:08
-
-
Save jgaskins/f57fbd703ba4c3a937d7d3bcdde26eb3 to your computer and use it in GitHub Desktop.
Array that does not let you mutate while inside an `each` block
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
class ImmutableEachArray(T) | |
include Enumerable(T) | |
@iterating = Atomic(Int32).new(0) | |
@array = Array(T).new | |
def <<(value : T) : self | |
raise CannotMutateWhileIterating.new("you iteratin bruh") if @iterating.get > 0 | |
@array << value | |
self | |
end | |
def each | |
@iterating.add 1 | |
@array.each { |i| yield i } | |
ensure | |
@iterating.sub 1 | |
end | |
class CannotMutateWhileIterating < Exception | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment