DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

Convert An Array To A Hash With Key Definitions

07.27.2006
| 24818 views |
  • submit to reddit
        First of all I'm relatively new to Ruby, so if there's a easier way
of doing this I would love to know about it :)

class Array
  def to_h(key_definition)
    result_hash = Hash.new()
    
    counter = 0
    key_definition.each do |definition|
      if not self[counter] == nil then
        result_hash[definition] = self[counter].strip
      else
        # Insert the key definition with a empty value.
        # Because we probably still want the hash to contain the key.
        result_hash[definition] = ""
      end
      # For some reason counter.next didn't work here....
      counter = counter + 1
    end
    
    return result_hash
  end
end

Use it like this:
key_definitions = Array['foo', 'bar', 'foobar', 'extra']
some_values     = Array['bla', 99, 'blabla']

some_values.to_h(key_definitions)   # => {'foo' => 'bla', 'bar' => 99, 'foobar' => 'blabla', 'extra' => ''}
    

Comments

Snippets Manager replied on Thu, 2007/03/29 - 8:30am

See also http://snippets.dzone.com/posts/show/302

Snippets Manager replied on Sun, 2007/02/04 - 7:37am

class Array def to_h(keys) Hash[*keys.flatten] end end

Snippets Manager replied on Sun, 2007/02/04 - 7:37am

Or even more compact class Array def to_h(keys) Hash[*key.flatten] end end

Snippets Manager replied on Thu, 2006/08/03 - 8:35pm

Another way to do it is class Array def to_h(keys) Hash[*keys.zip(self).flatten] end end It gives nils instead of ''s if the array is too short, though.