在这个Ruby代码未定义的方法错误链表

问题描述:

基本的问题,但我不明白为什么这个代码是生产上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) 

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

print_value是一种方法类别LinkedListNode。你不能在课堂外直接访问它。你需要一个类对象。

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

Learn more