re: Daily Coding Problem #3 VIEW POST

FULL DISCUSSION
 
require 'json'

class Node
  attr_accessor :v, :l, :r
  def initialize(v, l=nil, r=nil)
    self.v, self.l, self.r =
      case v
      when Hash
        left, right =
          %w|left right|.
            map { |node| v[node] }.
            map { |node| Node.new(node) unless node.to_s.empty? }
        [v['value'], left, right]
      when String
        [v, l, r]
      end
  end

  def to_s
    %Q|{"value":"#{v}","left":#{l || '""'},"right":#{r || '""'}}|
  end

  def ==(other)
    v == other.v && l == other.l && r == other.r
  end
end

# test
nn = Node.new('root', Node.new('left', Node.new('left.left')), Node.new('right'))
Node.new(JSON.parse nn.to_s) == nn
#⇒ true

Bonus: this serialization uses JSON format to make it easier to plug into other 3rd party code, if necessary.

 

My first time to see someone using Lua, thanks for the code, cool!

code of conduct - report abuse