Method: DataTools::ArrayOfHashes#key_on
- Defined in:
- lib/data_tools/array_of_hashes.rb
#key_on(*keyarray) ⇒ Object
convert an array of hashes to a hash of the same hashes where the key values are picked from the hashes the keys can be single fields, or an array, or a list options:
:multi (boolean, default false): if true, allow multiple values per key; store values as an array for each key
:first (boolean, default false): if true, when finding multiple values per key, store only the first and ignore the rest
:truncate (integer): see `Hash#key_for`
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/data_tools/array_of_hashes.rb', line 10 def key_on(*keyarray) raise "Key(s) required" if keyarray.empty? opts = keyarray.last.is_a?(Hash) ? keyarray.pop : {} keyarray = keyarray.flatten memo = opts[:multi] ? Hash.new {|h,k| h[k] = []} : Hash.new each do |hash| this_key = hash.key_for(keyarray, opts) raise "Missing value for #{keyarray} in record #{hash}" if this_key.nil? if opts[:multi] memo[this_key] << hash elsif opts[:first] # ignore this value if we already have one for this key if !memo.has_key?(this_key) memo[this_key] = hash end else raise "Found duplicate #{keyarray} in #{memo[this_key]} vs #{hash}" if memo.has_key?(this_key) memo[this_key] = hash end memo end memo.extend DataTools::HashOfArrays memo.default = nil memo end |