2015-04-17 64 views
1

基本的問題,但我不明白爲什麼這個代碼是生產上print_values的「未定義的方法」錯誤...在這個Ruby代碼未定義的方法錯誤鏈表

class LinkedListNode 
    attr_accessor :value, :next_node 

    def initialize(value, next_node=nil) 
     @value = value 
     @next_node = next_node 
    end 

    def print_values(list_node) 
     print "#{list_node.value} --> " 
     if list_node.next_node.nil? 
      print "nil\n" 
      return 
     else 
      print_values(list_node.next_node) 
     end 
    end 
end 

node1 = LinkedListNode.new(37) 
node2 = LinkedListNode.new(99, node1) 
node3 = LinkedListNode.new(12, node2) 

print_values(node3) 

回答

2

print_values是實例方法,因此您需要調用實例 (例如, node1.print_values(node1) 但在邏輯上應該是類方法即

def self.print_values(list_node) 
    #printing logic comes here 
end 

和,這樣稱呼它LinkedListNode.print_values(node_from_which_you want_to_print_linked_list)

+0

由於Anuja。顯然,我無法圍繞實例和類方法進行包裝(這裏只是一個初學者)。你可以推薦一些好的解釋來幫助澄清? – amongmany

+0

@amongmany你可以試試這個https://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/45-more-classes/lessons/113-class-variables –

+0

啊,謝謝。我做了RubyMonk入門,但沒有達到上升。 (有很多地方需要查看基礎知識,這很難找到並堅持一個。)我會檢查一下。 – amongmany

0

print_value是一種方法類別LinkedListNode。你不能在課堂外直接訪問它。你需要一個類對象。

node3.print_values(node3) 
# 12 --> 99 --> 37 --> nil 

Learn more