Skip to content

Instantly share code, notes, and snippets.

@practicingruby
Created June 18, 2012 19:55
Show Gist options
  • Select an option

  • Save practicingruby/2950366 to your computer and use it in GitHub Desktop.

Select an option

Save practicingruby/2950366 to your computer and use it in GitHub Desktop.
class BoundedStack
OverflowError = Class.new(StandardError)
invariant { data.size <= limit }
def initialize(limit)
self.data = []
self.limit = limit
end
def push(obj)
raise OverflowError if data.size >= limit
data.push(obj)
end
def pop
data.pop
end
# even without explicit error checking, attempting
# to construct a stack that exceeded the size limit
# would fail here.
def merge(other)
self.data = data + other.data
end
protected
attr_accessor :data, :limit
end
class BoundedStack
invariant("Can never have more elements than the limit") do
data.size <= limit
end
def initialize(limit)
self.data = []
self.limit = limit
end
def push(obj)
data.push(obj)
end
def pop
data.pop
end
def merge(other)
self.data = data + other.data
end
protected
attr_accessor :data, :limit
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment