Ruby中使用部分代码的单链表
我问了一个关于实现方法的问题,比如Ruby中使用部分代码的单链表,ruby,singly-linked-list,Ruby,Singly Linked List,我问了一个关于实现方法的问题,比如get\u item(index),或者find(value)和使用过的类 class SinglyLinkedListItem attr_accessor :object, :next attr_reader :list def initialize(object, list) @object = object @list = list end end class SinglyLinkedList attr_reader
get\u item(index)
,或者find(value)
和使用过的类
class SinglyLinkedListItem
attr_accessor :object, :next
attr_reader :list
def initialize(object, list)
@object = object
@list = list
end
end
class SinglyLinkedList
attr_reader :length
def initialize
@length = 0
@head = nil
@tail = nil
end
有一些方法,比如
def each
if @length > 0
item = @head
begin
yield item.object
item = item.next
end until item.nil?
end
end
我尝试了很多方法,但我仍然得到了这个错误:
NoMethodError: undefined method `object' for nil:NilClass
必须在nil上定义方法
#对象:
def nil.object; self end
错误不会以这种方式出现。我以前在使用attr\u访问器时遇到过这个问题
试着换一个新的
@#
与
作为预防措施,您可能需要检查item类
yield item.object unless item.nil?
例如:
def each
if self.length > 0
item = self.head
begin
yield item.object unless item.nil? #Check if item turned nil or not
item = item.next
end until item.nil?
end
end
您可能需要进行更多的处理,但您提供的数据并不能提供足够的信息。'item=@head除非@head.nil?'从错误语句中可以看出,您的头是错误的。你能告诉我们你用SingleLinkedListObject分配head的路径吗?每个方法都在工作,但例如find def find(object)item=@head while item!=如果item.object==object item=item.next end,则返回nil项nil end根本不工作。。。我已经写了我的修复程序,你能用你的编译器检查结果吗?谢谢,“编译器”?Ruby不是编译的,而是解释的。使用命令行中的-cwW2
标志运行代码,它会告诉您语法上的错误。@theTinMan:Ruby是一种编程语言,编程语言不解释也不编译,它们只是。编译和解释是编译器或解释器(duh)的特性,而不是语言。顺便说一句:除了(过时的)MRI之外,所有现有的主流Ruby实现(YARV、Rubinius、JRuby、IronRuby、MagLev、Topaz、MRuby、MacRuby)都有一个编译器。哼哼..建议定义一个单一
方法。它被称为vo_doo
编程范式。噢!我明白了,喜欢它…-)
def each
if self.length > 0
item = self.head
begin
yield item.object unless item.nil? #Check if item turned nil or not
item = item.next
end until item.nil?
end
end