-
-
Save practicingruby/2950366 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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 |
This file contains hidden or 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 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