Странная разница в поведении @var и attr_accessor в Ruby
Я обнаружил странную разницу в поведении экземпляра var (@var
) и attr_accessor
. Я верю, когда указано вattr_accessor
, var=some_value
должен вести себя так же, как @var=some_value
. Однако приведенный ниже фрагмент кода (реализация LinkedList в Ruby прерывается, когда не используется@
обозначение в строке 10. Кто-нибудь может объяснить, почему это происходит? Я тестировал 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