我正在尝试在装有3个托盘的ruby中创建一个Stack数据结构。它是一个LIFO数据结构,所以我添加到堆栈的最后一项应该是第一个出来的项目,但是我在收集数组中的项目时遇到困难,感觉我的语法错误只是为了在基本设置它方式。
代码:
class Stack
attr_reader :item
@@contents = []
def initialize(item)
@item = item
@@contents << item
end
def get_item
@contents.pop
end
end
@a = Stack.new("tray1")
@b = Stack.new("tray2")
@c = Stack.new("tray3")
答案 0 :(得分:4)
Array#push
和#pop
:
class Stack < Array; end # Ruby Array is good enough stack. Just subclass without ado.
s = Stack.new [ "tray1", "tray2" ]
#=> ["tray1", "tray2"]
s.pop
#=> "tray2"
s
#=> ["tray1"]
s.push "tray3"
#=> ["tray1", "tray3"]
s.pop
#=> "tray3" # last in first out
s.pop
#=> "tray1" # stack is empty now