Lampros - Weird Bricks

How to use JSON to serialize something in Ruby, save it to a file and read it back

15 November, 2014 | Jruby

This is mostly based on code samples from Stack Overflow which I didn't do a very good job of keeping track of the links.

All this has been tested on Jruby 1.7.16.1 which is compatible with Ruby 1.9.3 and can be tested in jirb

Serialize an Array into JSON and save it to a file:

require 'json'

# A very simple array
test_array = [1,2,3,4,5]

# Convert it to json and write it to a file
File.write('./lampros-test.txt', test_array.to_json)

# Then read it back:
test_array = JSON.parse(File.read('./lampros-test.txt'))

# Now add a couple more elements to the array:
test_array << 6
test_array << 7

# ...and save it again - this will overwrite the existing file:
File.write('./lampros-test.txt', test_array.to_json)

Now create an Array that we will populate with MD5 file hashes, save it to a file, read it back again and try comparing one of those files with the hashes in the array:

# Let's create an array that we will use to store MD5 hashes, it will be empty to start with:
md5_array = Array.new

# We'll create MD5 hashes out of 3 test files and insert those in the array:

require 'json'
require 'digest'

# this will create an MD5 digest out of each of the files and "push" it to the array
md5_array.push(Digest::MD5.file './test1.txt')
md5_array.push(Digest::MD5.file './test2.txt')
md5_array.push(Digest::MD5.file './test3.txt')

# Now save this to the JSON as before:
File.write('./lampros-test.txt', md5_array.to_json)

# Read it back:
md5_array = JSON.parse(File.read('./lampros-test.txt'))

# Note that when we get the array back the objects inside the array are class String not class Digest!!!
md5_array[1].class
#=> String

# Check if one the hash of one of those files exist in the md5_array:
md5_array.include? (Digest::MD5.file './test2.txt').to_s
# => true