Ruby convert Object to Hash

ma11hew28 picture ma11hew28 · Feb 17, 2011 · Viewed 136.5k times · Source

Let's say I have a Gift object with @name = "book" & @price = 15.95. What's the best way to convert that to the Hash {name: "book", price: 15.95} in Ruby, not Rails (although feel free to give the Rails answer too)?

Answer

Austin Marusco picture Austin Marusco · Nov 3, 2012

Just say (current object) .attributes

.attributes returns a hash of any object. And it's much cleaner too.