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 :)

   1  
   2  class Array
   3    def to_h(key_definition)
   4      result_hash = Hash.new()
   5      
   6      counter = 0
   7      key_definition.each do |definition|
   8        if not self[counter] == nil then
   9          result_hash[definition] = self[counter].strip
  10        else
  11          # Insert the key definition with a empty value.
  12          # Because we probably still want the hash to contain the key.
  13          result_hash[definition] = ""
  14        end
  15        # For some reason counter.next didn't work here....
  16        counter = counter + 1
  17      end
  18      
  19      return result_hash
  20    end
  21  end


Use it like this:
   1  
   2  key_definitions = Array['foo', 'bar', 'foobar', 'extra']
   3  some_values     = Array['bla', 99, 'blabla']
   4  
   5  some_values.to_h(key_definitions)   # => {'foo' => 'bla', 'bar' => 99, 'foobar' => 'blabla', 'extra' => ''}
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS