to_h in ruby 2.0

With few major changes ruby 2.0 is out today, out the many new features I really liked the to_h

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

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

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

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

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
# => {: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 =,:age) do
alias to_hash to_h
p ["abc",30)].map {|**p| p }
# Would put : [{:name=>"abc", :age=>30}]

Share this