Method: Sequel::Dataset#as_hash

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

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

Returns a hash with one column used as key and another used as value. If rows have duplicate values for the key column, the latter row(s) will overwrite the value of the previous row(s). If the value_column is not given or nil, uses the entire hash as the value.

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

DB[:table].as_hash(:id) # SELECT * FROM table
# {1=>{:id=>1, :name=>'Jim'}, 2=>{: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].as_hash([:id, :foo], [:name, :bar]) # SELECT * FROM table
# {[1, 3]=>['Jim', 'bo'], [2, 4]=>['Bob', 'be'], ...}

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

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.



910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
# File 'lib/sequel/dataset/actions.rb', line 910

def as_hash(key_column, value_column = nil, opts = OPTS)
  h = opts[:hash] || {}
  meth = opts[:all] ? :all : :each
  if value_column
    return naked.as_hash(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