reitermarkus reitermarkus - 6 months ago 7
Ruby Question

What's the best way to refactor insert_after and insert_before methods for a linked-list node?

I already tried using the

send
method, but it ended up being almost unreadable and as long as the previous code. Is there a simple way in Ruby to refactor code like this?

def insert_before(data)
node = Node.new(data)
node.next = self
node.prev = @prev

@prev.next = node unless @prev.nil?

@prev = node
end

def insert_after(data)
node = Node.new(data)
node.prev = self
node.next = @next

@next.prev = node unless @next.nil?

@next = node
end

Answer

I think what you have is fine, but you may want to put the common bits of the two methods in a separate method.

def insert_before(data)
  node = insert_node(data, self, @prev)
  @prev.next = node unless @prev.nil?
  @prev = node
end

def insert_after(data)
  node = insert_node(data, @next, self)
  @next.prev = node unless @next.nil?
  @next = node
end

def insert_node(data, from, to)
  node = Node.new(data)
  node.next = to
  node.prev = from
  node
end
Comments