2012-02-07 75 views
-3

要學習Ruby,我要實現以節點和簡單堆棧開始的不同數據結構。如果我將每個def與相應的結尾相匹配,那麼期待$ end(EOF)會出現很多錯誤,但會得到end。所以我可以通過在課程結束時堆疊一些end來修復它,但顯然我不知道爲什麼這會起作用。在Ruby中匹配結束標記

require "Node" 
class Stack 
    attr_accessor :top 

    def size 
      @size 
    end 

    def push(node) 
     if node && node.next 
      node.next = top 
      top = node 
     end 
     size++ 
    def pop() 
     if top != nil 
      top = top.next 
     end 
     size-- 


    def to_s 
     if top != nil 
      temp = top 
      while temp != nil 
       puts temp.value 
       temp = temp.next 
      end 
     else 
      puts "The stack is empty" 
     end 
    end 
end 
end 
end 

節點類很簡單,應該不會造成任何問題:

class Node 
    attr_accessor :next 
    def initialize(value) 
     @value = value 
    end 
end 

一切正常的弗蘭肯斯坦堆棧,除了在NoMethodError: undefined method [email protected]' for nil:NilClass推節點結果。不知道這是否有關,但我主要關注方法/類聲明的語法和使用方法end

回答

1

你會得到一個錯誤,因爲ruby沒有++--操作符。

紅寶石理解以下構造

size++ 
def pop() 
# and 
size-- 
def to_s() 

size + +def pop() 
# and 
size - -def to_s() 

紅寶石語法表達導向和方法定義是紅寶石表達。方法定義表達式(def pop()def to_s())評估爲nil(在您的代碼中,您實際上在push方法體內部定義了方法pop,在pop方法體內部定義了to_s)。這就是爲什麼你會得到NoMethodError: undefined method [email protected]' for nil:NilClass錯誤 - 它評估表達式size + +nil和nil沒有定義一元加運算符。在該表達式中,第一個+Fixnum加法運算符(sizeFixnum),並且第二個+是一元加運算符nil(結果爲def pop()表達式)。

使用+= 1-= 1而不是++--。你的代碼應該是這樣的:

class Stack 
    attr_accessor :top 

    def size 
      @size 
    end 

    def push(node) 
     if node && node.next 
      node.next = top 
      top = node 
     end 
     @size += 1 # @size, not `size` because you have `size` getter and you cannot modify size with getter method 
    end 

    def pop() 
     if top != nil 
      top = top.next 
     end 
     @size -= 1 
    end 

    def to_s 
     if top != nil 
      temp = top 
      while temp != nil 
       puts temp.value 
       temp = temp.next 
      end 
     else 
      puts "The stack is empty" 
     end 
    end 
end 
0

您的def s沒有匹配end。另外,Ruby沒有++運算符;您必須改用+= 1

+0

根據這個問題,OP有他們所屬的'end's,但是它給了他語法錯誤。這就是爲什麼他將他們刪除(這不是最明智的決定)。 – 2012-02-07 20:34:15

+0

@NiklasB .:當然,這個OP在他的假設中是不正確的。 Ruby解析器按照規範工作,語法錯誤在其他地方,或者他計算他的def/end對錯誤。 – 2012-02-07 20:35:07

+0

@Ed S .:是的,句法問題是'++',可能使用'next'作爲方法名稱(雖然不確定)。 – 2012-02-07 20:41:17