-
-
Save flada-auxv/4200213 to your computer and use it in GitHub Desktop.
The stack from my Pry screencast
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
# The stack I wrote for http://vimeo.com/26391171 | |
# Note that there is an intentional bug in the each method :) | |
class Stack | |
Node = Struct.new :data, :next | |
def push(data) | |
@head = Node.new data, @head | |
end | |
def pop | |
return unless @head | |
data = @head.data | |
@head = @head.next | |
data | |
end | |
## | |
# Iterates across the stack | |
# | |
# stack = Stack.new | |
# stack.push 5 | |
# stack.push "abc" | |
# array = [] | |
# stack.each { |element| array << element } | |
# array # => ["abc", 5] | |
def each | |
crnt = @head | |
loop do | |
yield crnt.data | |
crnt = crnt.next | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment