0

I want to replace the below (non DRY) code:

dir = value > node.data ? "right" : "left"

if value > node.data
  if node.right.nil?
    node.right = Node.new(value)
  else
    insert(value, node.right)
  end
else
  if node.left.nil?
    node.left = Node.new(value)
  else
    insert(value, node.left)
  end
end

with something like this:

dir = value > node.data ? "right" : "left"
if node.dir.nil?
  node.dir = Node.new(value)
else
  insert(value, node.dir)
end

Node is a struct defined like so:

Node = Struct.new(:data, :left, :right)

How can I do this?

1 Answer 1

1

Since it's a struct, you can use [:left] or [:right] instead of .left and .right.

Therefore, you can

dir = value > node.data ? :right : :left
if node[dir].nil?
  node[dir] = Node.new(value)
else
  insert(value, node[dir])
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.