[分享] 第一篇含有程式碼的文章 -- 堆疊

看板Ruby作者 (CFC)時間18年前 (2006/05/19 16:15), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串1/1
要是感覺看得很辛苦可以到 http://www.wretch.cc/blog/cfcef&article_id=5631452 觀看線上版 XD class Stack def initialize ary=0, max=0, lvl=0 @ary = ary @max = max @lvl = lvl end def add if @lvl < @max puts "Please input a value for add to the stack!" @ary[@lvl] = self.get_value @lvl+=1 puts "Now you have #{@lvl} elements for the array!" else puts "Stack is full!" end end def del puts "#{@ary[@lvl-1]} has been removed!" @lvl -= 1 if @lvl <= 0 puts "You have no element in the array!" else puts "Now you have #{@lvl} elements in the array!" end end def get_value return gets.chomp end def list if @lvl <= 0 puts "You have no element in the array!" else for ele in 0 ... @lvl puts @ary[ele] end end true end public :initialize, :add, :del, :list protected :get_value end puts "Please input a number for the stack max!" ary = {} max = gets.chomp.to_i lvl = 0 stack = Stack.new(ary, max, lvl) =begin Actions: 1. add -- for add elements 2. del -- for remove elements 3. list -- for list elements 4. exit -- end this program =end while true puts "Please select a action!" puts <<EOF Actions: 1. add -- for add elements 2. del -- for remove elements 3. list -- for list elements 4. exit -- end this program EOF action = gets.chomp case action when "add" ,"1" puts "Adding array element!" stack.add when "del", "2" puts "Removing array element!" stack.del when "list", "3" puts "Listing array elements!" stack.list when "exit", "4" puts "Bye~ bye!" exit end end -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 211.74.252.74
文章代碼(AID): #14RNwN7f (Ruby)
文章代碼(AID): #14RNwN7f (Ruby)