Method: Sequel::Dataset#to_hash
- Defined in:
- lib/sequel/dataset/actions.rb
#to_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].to_hash(:id, :name) # SELECT * FROM table
# {1=>'Jim', 2=>'Bob', ...}
DB[:table].to_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].to_hash([:id, :foo], [:name, :bar]) # SELECT * FROM table
# {[1, 3]=>['Jim', 'bo'], [2, 4]=>['Bob', 'be'], ...}
DB[:table].to_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.
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 |
# File 'lib/sequel/dataset/actions.rb', line 727 def to_hash(key_column, value_column = nil, opts = OPTS) h = opts[:hash] || {} meth = opts[:all] ? :all : :each if value_column return naked.to_hash(key_column, value_column, opts) if row_proc if value_column.is_a?(Array) if key_column.is_a?(Array) send(meth){|r| h[r.values_at(*key_column)] = r.values_at(*value_column)} else send(meth){|r| h[r[key_column]] = r.values_at(*value_column)} end else if key_column.is_a?(Array) send(meth){|r| h[r.values_at(*key_column)] = r[value_column]} else send(meth){|r| h[r[key_column]] = r[value_column]} end end elsif key_column.is_a?(Array) send(meth){|r| h[key_column.map{|k| r[k]}] = r} else send(meth){|r| h[r[key_column]] = r} end h end |