# How to Convert a Ruby Object to Hash

*Published on May 01, 2022*

---


Let’s say you have a&nbsp;`Product`&nbsp;object with properties&nbsp;`@name = "Table"`&nbsp;&&nbsp;`@price = 10`. What’s the best way in Rails to convert this object to the Hash&nbsp;`{ name: "Table", price: 10 }`?

Here're a few different ways to achieve this.

## The as\_json Method (Rails)

The&nbsp;[`as_json`](https://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html#method-i-as_json)&nbsp;method converts a model to a hash, containing the attributes with their names as keys and the values of the attributes as values

```ruby
user = User.find(1)
user.as_json
# => { "id" => 1, "name" => "Konata Izumi", "age" => 16 }
```

Additionally, you can include the model itself as the root of the object.

```ruby
user = User.find(1)
user.as_json(root: true)
# => { "user" => { "id" => 1, "name" => "Konata Izumi", "age" => 16 } }
```

This method also gives you more control over the resulting JSON representation. For example, you can use the&nbsp;`:only`&nbsp;and&nbsp;`:except`&nbsp;options to select which attributes you want to include and skip, respectively. For more details, refer the&nbsp;[documentation](https://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html#method-i-as_json).

## The&nbsp;_attributes_&nbsp;Method (Rails)

The&nbsp;[`ActiveRecord#attributes`](https://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods.html#method-i-attributes)&nbsp;is another method you can use. Given an active record,&nbsp;`attributes`&nbsp;returns a hash of all the attributes with their names as keys and the values of the attributes as values.

```ruby
class Person < ActiveRecord::Base
end

person = Person.create(name: 'Francesco', age: 22)
person.attributes
# => {"id"=>3, "created_at"=>Sun, 21 Oct 2012 04:53:04, "updated_at"=>Sun, 21 Oct 2012 04:53:04, "name"=>"Francesco", "age"=>22}
```

The&nbsp;`attributes`&nbsp;method returns a hash where all the keys are strings. If you want, it’s easy to symbolize the hash using the aptly named&nbsp;[`symbolize_keys`](https://api.rubyonrails.org/classes/Hash.html#method-i-symbolize_keys)&nbsp;method or its alias&nbsp;`to_options`.

```ruby
hash = { 'name' => 'Rob', 'age' => '28' }

hash.symbolize_keys
# => {:name=>"Rob", :age=>"28"}
```

## The Ruby Way

If you are looking for a plain Ruby solution, you can do this using metaprogramming.

For this, you will need two methods:

1. `instance_variables`&nbsp;returns an array of object’s instance variables.
2. `instance_variable_get`&nbsp;returns the value of the instance variable, given the variable name.

With that, you could do something like this:

```ruby
hash = Hash.new
record.instance_variables.each do |v| 
  hash[v.to_s.delete("@")] = record.instance_variable_get(v) 
end
```

**What do you think? Did I miss anything?**

