0

I am learning Ruby and am wondering how to serialize a ruby object to json. I am cool using ActiveSupport or any other gems, what is the best way to to this? The following approach doesn't work and fails with

BinaryTree.rb:4:in `require': no such file to load -- json (LoadError)

My question is, what do I install and what require statements would I need to use?

 #!/usr/bin/env ruby

 require 'pp'
 require 'json'

 class BinaryTree

     attr_accessor :key, :value, :left, :right

     def initialize(key=nil,value=nil, left=nil, right=nil)
         @key, @value, @left, @right = key, value, left, right
     end

     def insert(key,value)
         if @key.nil?
             @key = key
             return @value = value
         end

         if key == @key
             return @value = value
         end

         if key > @key
             if @right.nil?
                 @right = BinaryTree.new
             end
             return @right.insert(key, value)
         end

         if @left.nil?
             @left = BinaryTree.new
         end
         return @left.insert(key, value)
     end
 end

 if __FILE__ == $0
     bt = BinaryTree.new
     bt.insert(5,2)
     bt.insert(4,5)
     bt.insert(6,3)
     bt.insert(9,7)
     bt.insert(8,9)
     pp bt
     puts JSON.encode(bt)
end
David Williams
  • 8,388
  • 23
  • 83
  • 171
  • 1
    see this: http://stackoverflow.com/questions/4569329/serialize-ruby-object-to-json-and-back and http://stackoverflow.com/questions/4464050/ruby-objects-and-json-serialization-without-rails – rjurado01 Mar 16 '13 at 23:05

1 Answers1

1

Do you have the json gem installed? If not, you'd need to ensure you install that using gem install json first. Once installed, you should be able to do something like the following:

File.open('output_file', 'w') do |f|
  f.write(JSON.encode(bt))
end

Using the File.open API with a block is convenient since it will #close the file instance afterward.

Update

If you're on Ruby 1.8 or earlier, you must set up Rubygems first, using the following:

require 'rubygems'
gem 'json'
require 'json'

puts ['test'].to_json
Stuart M
  • 11,458
  • 6
  • 45
  • 59
  • I think that I do, but maybe its not being found? Is there an include type of argument I need to pass to the interpreter? `$ sudo gem install json Building native extensions. This could take a while... Successfully installed json-1.7.7 1 gem installed Installing ri documentation for json-1.7.7... Installing RDoc documentation for json-1.7.7... $ ruby BinaryTree.rb BinaryTree.rb:4:in `require': no such file to load -- json (LoadError) from BinaryTree.rb:4 ` – David Williams Mar 17 '13 at 16:51
  • Oh, are you on Ruby 1.8? If so, you'll need to manually `require 'rubygems'` and call `gem 'json'` first. I've updated my answer with details. – Stuart M Mar 17 '13 at 21:31