Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Convert an array to a hash (See related posts)

Pretty simple, but maybe not intuitive
class Array
  def to_h
    Hash[*self]
  end
end

Use it like this:
['action', 'go', 'id', 6].to_h   # => { 'action' => 'go', 'id' => 6 }

Comments on this post

vidul posts on Oct 26, 2006 at 14:51
class Array
  def to_h
    arr = self.dup
    if arr.size % 2 == 0
        Hash[*arr]
    else
        Hash[*arr << nil]
    end
  end
end

You need to create an account or log in to post comments to this site.


Click here to browse all 4852 code snippets

Related Posts