Andrii Furmanets Andrii Furmanets - 1 year ago 78
Ruby Question

Hamster.vector troubles with converting to json

I'm working with

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
=> "{\"levels\":0,\"root\":[],\"size\":0}" # what is this?

So, my question is:

Can someone explain me why
keys to the object and how can I remove them from my json.

Answer Source
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download