Method: Array#to_h_auto
- Defined in:
- lib/core/facets/to_hash.rb
#to_h_auto ⇒ Object
Converts an array into a hash. Converting an array into a hash is not a one-to-one conversion, for this reason #to_h examines at the array being converted and then dispatches the conversion to the most sutiable specialized function. There are three possiblities for this.
If the array is a collection of perfect pairs, like that which Hash#to_a generates, then conversion is handled by #to_h_flat.
a = [ [:a,1], [:b,2] ]
a.to_h_auto #=> { :a=>1, :b=>2 }
If the array contains only arrays, but are not perfect pairs, then #to_h_multi is called.
a = [ [:a,1,2], [:b,2], [:c], [:d] ]
a.to_h_auto #=> { :a=>[1,2], :b=>[2], :c=>[], :d=>[] }
If the array contians objects other then arrays then the #to_h_splat method is called.
a = [ [:a,1,2], 2, :b, [:c,3], 9 ]
a.to_h_auto #=> { [:a,1,2]=>2, :b=>[:c,3], 9=>nil }
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
# File 'lib/core/facets/to_hash.rb', line 91 def to_h_auto pairs = true mixed = false each do |e| case e when Array pairs = false if e.size > 2 else mixed = true end end if mixed to_h_splat elsif pairs to_h_flat else to_h_multi end end |