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
Convert An Array To A Hash With Key Definitions
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
Snippets Manager replied on Sun, 2007/02/04 - 7:37am
class Array def to_h(keys) Hash[*keys.flatten] end endSnippets Manager replied on Sun, 2007/02/04 - 7:37am
class Array def to_h(keys) Hash[*key.flatten] end endSnippets Manager replied on Thu, 2006/08/03 - 8:35pm
class Array def to_h(keys) Hash[*keys.zip(self).flatten] end endIt gives nils instead of ''s if the array is too short, though.