Ruby convert Object to Hash Ruby convert Object to Hash ruby ruby

Ruby convert Object to Hash


Just say (current object) .attributes

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


class Gift  def initialize    @name = "book"    @price = 15.95  endendgift = Gift.newhash = {}gift.instance_variables.each {|var| hash[var.to_s.delete("@")] = gift.instance_variable_get(var) }p hash # => {"name"=>"book", "price"=>15.95}

Alternatively with each_with_object:

gift = Gift.newhash = gift.instance_variables.each_with_object({}) { |var, hash| hash[var.to_s.delete("@")] = gift.instance_variable_get(var) }p hash # => {"name"=>"book", "price"=>15.95}


Gift.new.instance_values # => {"name"=>"book", "price"=>15.95}