Andrii Furmanets Andrii Furmanets - 6 months ago 20
Ruby Question

Hamster.vector troubles with converting to json

I'm working with

Hamster
gem in my project and I faced with problem when serializing to json.
Here is what I'm toking about:

hamster = Hamster.vector()
=> [] #is empty
hamster.to_json
=> "{\"levels\":0,\"root\":[],\"size\":0}" # what is this?


So, my question is:

Can someone explain me why
Hamster
adding
levels
,
root
and
size
keys to the object and how can I remove them from my json.

Answer
hamster = Hamster.vector()
 => [] #is empty

Hamster.vector() returns a singleton instance(EmptyVector) of Hamster::Vector class.

[] is displayed as an output because Enumerable#reduce is overridden by Hamster.

levels, root and size are instance variables of Class Hamster::Vector which are initialized in Hamster::Vector#initialize method.

So when you hamster.to_json you see the output as

 => "{\"levels\":0,\"root\":[],\"size\":0}"

Use Hamster::Vector#empty? method to check if your hamster object is empty? i.e., @size == 0

hamster.to_json unless hamster.empty?

This way if hamster is an empty object you don't convert it to json.

Comments