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 with key definitions (See related posts)

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 on this post

Murt posts on Aug 03, 2006 at 20:48
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.
NeRMe posts on Feb 04, 2007 at 06:57
Or even more compact


class Array
def to_h(keys)
Hash[*key.flatten]
end
end
</code
NeRMe posts on Feb 04, 2007 at 06:58
class Array
  def to_h(keys)
    Hash[*keys.flatten]
  end
end
petef posts on Mar 29, 2007 at 08:37
See also http://snippets.dzone.com/posts/show/302

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