Last active
August 13, 2018 11:29
-
-
Save xvw/0907043f3c31cf9a08311fd7b8b019ee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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