---
title: "Hemanth.HM"
description: "With few major changes ruby 2.0 is out today, out the many new features I really liked the toh We can convert a class to a."
url: "https://h3manth.com/scribe/to-h-ruby-20/"
canonical_url: "https://h3manth.com/scribe/to-h-ruby-20/"
markdown_url: "https://h3manth.com/scribe/blog/to-h-ruby-20.md"
publishDate: "2012-01-01T00:00:00.000Z"
author: "Hemanth HM"
category: "web"
tags: ["ruby","git"]
word_count: 186
reading_time_minutes: 1
x_markdown_tokens: 396
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# Hemanth.HM

> With few major changes ruby 2.0 is out today, out the many new features I really liked the toh We can convert a class to a.

With few major changes ruby 2.0 is out today, out the many [new features](https://github.com/marcandre/ruby/blob/news/NEWS.rdoc) I really liked the **to_h**

We can convert a class to a Hash, using `to_h`:

``
    
    
    # Ruby 2.0:
    Student = Struct.new(:name, :age, :year) do
      def info
        #...
      end
    end
    dude = Student.new('Hemanth', '16', 2)
    dude.to_h # => {:name=>"Hemanth", :age=>"16", :year=>2}
    nil.to_h # => {}
    

P.S : This has been implemented for `nil`, `Struct` and `OpenStruct`, but not for `Enumerable`/`Array`, so :

` module Enumerable # mapping array into a hash def to_h(&block)`
    
    
    inject({}) {|hash, *v| block.call(hash, *v); hash}
    

end end 

After which we can use to_h on Array and other enumarations :

` a = [:count, nil].to_h do |hash, value| hash[value] = 1 if value end`

## => {:count=>1}

P.S : I tired this by doing : ` rvm install 2.0.0-p0` && `rvm use ruby-2.0.0-p0` rvm++ :)

Do feel free to share you liking towards any other new feature.

**Update 0 thanks to Hanmac :**

Some fun to ** and to_h.

` Person = Struct.new(:name,:age) do alias to_hash to_h end`

p [Person.new("abc",30)].map {|**p| p }

## Would put : [{:name=>"abc", :age=>30}]
