CSC/ECE 517 Fall 2013/ch1 1w05 st: Difference between revisions
No edit summary |
No edit summary |
||
Line 19: | Line 19: | ||
== Converting Ruby Objects in Human Readable Formats == | === Converting Ruby Objects in Human Readable Formats === | ||
== ''Converting Ruby Objects to YAML format'' == | ==== ''Converting Ruby Objects to YAML format'' ==== | ||
YAML[http://yaml.org/] format is a human friendly data serialization standard for all programming languages. Any Ruby object can easily be serialized into YAML format. Let us consider the below code, | YAML[http://yaml.org/] format is a human friendly data serialization standard for all programming languages. Any Ruby object can easily be serialized into YAML format. Let us consider the below code, | ||
{{{ | |||
require "yaml" | require "yaml" | ||
class First | class First | ||
Line 37: | Line 37: | ||
end | end | ||
end | end | ||
class Second | class Second | ||
def initialize(address, details) | def initialize(address, details) | ||
Line 52: | Line 52: | ||
y = Second.new("St. Marks Street", x) | y = Second.new("St. Marks Street", x) | ||
puts y | puts y | ||
}}} |
Revision as of 18:17, 17 September 2013
Serialization
Serialization[1] is the process of converting an object or a group of objects into a stream of bytes or string to facilitate storage in memory or transmission over a network. The process of Serialization is also referred to as Marshalling. De-serialization is the process of converting the stream of bytes or string back to objects in memory. This process of de-serialization is also referred to as Unmarshalling.
Serialization in Ruby:
Let us consider a situation where two Ruby programs have to communicate with each other. One of the simplest way to do this is to convert the Ruby objects in the first programs into strings and writing these strings into a file. This is nothing but serialization. The second program can read this file and convert the strings back into Ruby objects. This is de-serialization.
Types of Serialization
Serialization in Ruby can be done in two ways. During serialization, the object in memory can be converted into Human Readable formats like YAML (YAML Ain’t Markup Language) and JSON (JavaScript Object Notation), or the object can be converted into binary format.
Converting Ruby Objects in Human Readable Formats
Converting Ruby Objects to YAML format
YAML[2] format is a human friendly data serialization standard for all programming languages. Any Ruby object can easily be serialized into YAML format. Let us consider the below code, {{{ require "yaml"
class First def initialize(name, age, country)
@name = name @age = age @country=country
end def to_s
"In First:\n#{@name}, #{@age}, #{@country}\n"
end
end
class Second
def initialize(address, details)
@address = address @details = details
end def to_s
"In Second:\n#{@details.to_s}#{@address}\n"
end
end
x = First.new("Tom", 25, "USA") y = Second.new("St. Marks Street", x) puts y }}}