Method: Sequel::Dataset#to_hash_groups

Defined in:
lib/sequel/dataset/actions.rb

#to_hash_groups(key_column, value_column = nil, opts = OPTS) ⇒ Object

Returns a hash with one column used as key and the values being an array of column values. If the value_column is not given or nil, uses the entire hash as the value.

DB[:table].to_hash_groups(:name, :id) # SELECT * FROM table
# {'Jim'=>[1, 4, 16, ...], 'Bob'=>[2], ...}

DB[:table].to_hash_groups(:name) # SELECT * FROM table
# {'Jim'=>[{:id=>1, :name=>'Jim'}, {:id=>4, :name=>'Jim'}, ...], 'Bob'=>[{:id=>2, :name=>'Bob'}], ...}

You can also provide an array of column names for either the key_column, the value column, or both:

DB[:table].to_hash_groups([:first, :middle], [:last, :id]) # SELECT * FROM table
# {['Jim', 'Bob']=>[['Smith', 1], ['Jackson', 4], ...], ...}

DB[:table].to_hash_groups([:first, :middle]) # SELECT * FROM table
# {['Jim', 'Bob']=>[{:id=>1, :first=>'Jim', :middle=>'Bob', :last=>'Smith'}, ...], ...}

Options:

:all

Use all instead of each to retrieve the objects

:hash

The object into which the values will be placed. If this is not given, an empty hash is used. This can be used to use a hash with a default value or default proc.



965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
# File 'lib/sequel/dataset/actions.rb', line 965

def to_hash_groups(key_column, value_column = nil, opts = OPTS)
  h = opts[:hash] || {}
  meth = opts[:all] ? :all : :each
  if value_column
    return naked.to_hash_groups(key_column, value_column, opts) if row_proc
    if value_column.is_a?(Array)
      if key_column.is_a?(Array)
        public_send(meth){|r| (h[r.values_at(*key_column)] ||= []) << r.values_at(*value_column)}
      else
        public_send(meth){|r| (h[r[key_column]] ||= []) << r.values_at(*value_column)}
      end
    else
      if key_column.is_a?(Array)
        public_send(meth){|r| (h[r.values_at(*key_column)] ||= []) << r[value_column]}
      else
        public_send(meth){|r| (h[r[key_column]] ||= []) << r[value_column]}
      end
    end
  elsif key_column.is_a?(Array)
    public_send(meth){|r| (h[key_column.map{|k| r[k]}] ||= []) << r}
  else
    public_send(meth){|r| (h[r[key_column]] ||= []) << r}
  end
  h
end