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

About this user

Eloy Duran

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

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' => ''}
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS