In this case, person.to_json does not do what you expect.
When you require 'json' , the JSON library inserts the #to_json method on an Object , which is fallback unless there is a specialized #to_json method provided elsewhere. This inserted method is basically the same as calling #to_s#to_json for an object.
In the case of your Person class, here #to_s displays the Object#to_s , which by default does not provide string parsing by the JSON library.
However, Struct provides a #to_h method that can be used to convert this structure to Hash , and Hash (with a JSON library) knows how to generate JSON parsing.
So a simple change:
json = Person.new('Adam', 19).to_json puts json
in
person = Person.new('Adam', 19) puts person.to_h.to_json
will do what you expect.
(As an aside, I would recommend implementing #to_json in the Person class directly, since calling #to_h#to_json violates the Law of Demeter .)
source share