Skip to content

Instantly share code, notes, and snippets.

@xvw
Last active August 13, 2018 11:29
Show Gist options
  • Save xvw/0907043f3c31cf9a08311fd7b8b019ee to your computer and use it in GitHub Desktop.
Save xvw/0907043f3c31cf9a08311fd7b8b019ee to your computer and use it in GitHub Desktop.
class Human
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
end
# Serialization (to JSon) by hand
def to_json
"{\"name\": \"#{@name}\", \"age\": #{@age}}"
end
# Dump in file (using Marshal)
def to_file(file)
File.open(file, 'wb') do | channel |
serialized = Marshal.dump(self)
channel.write(serialized)
end
end
# Load from file (using Marshal)
def self.from_file(file)
File.open(file, 'rb') do | channel |
Marshal.load(channel)
end
end
end
# Initialize data
xavier = Human.new('Xavier', 28)
antoine = Human.new('Antoine', 34)
# Serialize to Json
puts xavier.to_json
puts antoine.to_json
# Dump into a file
xavier.to_file('xavier.data')
antoine.to_file('antoine.data')
# Retreive data from a file
xavier2 = Human.from_file('xavier.data')
antoine2 = Human.from_file('antoine.data')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment