代码
module StackLike
def stack
@stack ||=[]
end
def add_to_stack(obj)
stack.push(obj)
end
def take_from_statck
statck.pop
end
end
class Statck
include Stacklike
end
s=Statck.new
s.add_to_statck(“item one”)
s.add_to_statck(“item_two”)
s.add_to_statck(“item three”)
puts “Object current on the statck”
puts s.stack
taken=s.take_from_stack
puts “Removed this object:”
puts taken
puts “now on statck”
puts s.stack
运行结果
Objects current on the stack
item one
item two
item threee
remove this object
item three
Now on stack
item one
item two