I found weird behavior difference between an instance var (@var
) and an attr_accessor
. I believe when specified in attr_accessor
, var=some_value
should behave the same as @var=some_value
. However, the below code snippet (LinkedList implementation in Ruby breaks when not using @
notation in line 10. Can anyone explain why this happens? I have tested in Ruby 2.6.1 and 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