Just imagine a situation when the only information we know about Ruby’s object is it’s human readable format:
#<User::Class::Element:0x2fef43 @field1 = 1, @field2 = two, @field3 = [1,2,3]>
The task is to write a method which could convert this representation to the object of the class pointed by this representation (of course with having an access to all appropriate namespaces, modules, classes and methods). For example:
obj = humanReadableFormat2Obj("#<User::Class::Element:0x2fef43 @field1 = 1, @field2 = \"two\", @field3 = [1,2,3]>")
puts obj.field1 #=> "1"
puts obj.field2 #=> "two"
p obj.field3 #=> [1, 2, 3]
puts obj.class.to_s #=> User::Class::Element
P.S. This task originates from the problem of synchronization of several large data bases. Instead of transfering objects from one data base to another in the binary format(hundreds of MB) you can transfer only a script (several KB) and execute it on another data base to create appropriate object.
The Ox and Oj gems (XML and JSON respectively) can serialize into relatively human readable Ruby objects. This would probably be a better solution, since the
inspectmethod doesn’t always return all of the attributes of a Ruby object, as Sigurd mentioned in the comments.Example from the Ox docs: