我发现实例 var( @var
) 和attr_accessor
. 我相信当在 中指定时attr_accessor
,var=some_value
其行为应该与@var=some_value
. 但是,下面的代码片段(在第 10 行中不使用符号时,Ruby 中的 LinkedList 实现会中断@
。谁能解释为什么会发生这种情况?我已经在 Ruby 2.6.1 和 2.6.5 中进行了测试。
class LinkedList
def initialize
self.head = nil
self.tail = nil
end
def add_first(data)
if @head.nil?
@head = Node.new(data) # Break if I use head without @
@tail = @head
else
@head = Node.new(data, @head)
end
end
def add_last(data);
if @tail
@tail.next_node = Node.new(data)
@tail = @tail.next_node
else
add_first(data)
end
end
def to_s
result_str = ""
curr_node = @head
until (curr_node.next_node.nil?)
result_str << curr_node.data << ", "
curr_node = curr_node.next_node
end
# Last data is a special case without a comma
result_str << curr_node.data
end
protected
attr_accessor :head, :tail
end
class Node
attr_accessor :data, :next_node
def initialize(data=nil, next_node=nil)
self.data = data
self.next_node = next_node
end
def to_s
data.to_s
end
end
head = LinkedList.new
head.add_first("First")
head.add_first("Second")
head.add_first("Third")
head.add_last("Chicago")
head.add_last("Vegas")
puts head