The best way to convert an Object to Hash in Ruby:
1 2 3 4 5 6 7 8 9 10 11 |
class Gift def initialize @name = "book" @price = 15.95 end end gift = Gift.new hash = {} gift.instance_variables.each {|var| hash[var.to_s.delete("@")] = gift.instance_variable_get(var) } p hash # => {"name"=>"book", "price"=>15.95} |
Source: Stackoverflow