Skip to content

Instantly share code, notes, and snippets.

@jgaskins
Last active January 5, 2022 20:08
Show Gist options
  • Save jgaskins/f57fbd703ba4c3a937d7d3bcdde26eb3 to your computer and use it in GitHub Desktop.
Save jgaskins/f57fbd703ba4c3a937d7d3bcdde26eb3 to your computer and use it in GitHub Desktop.
Array that does not let you mutate while inside an `each` block
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