Class Enumerable::Hashifier
In: lib/core/facets/enumerable/hashify.rb
Parent: Object

Methods

assoc   associate   auto   automatic   by_index   concat   flat   merge   multi   new   splat  

Public Class methods

Public Instance methods

assoc()

Alias for associate

When a mixed or multi-element associative array is used, the result is as follows:

  a = [ [:a,1,2], [:b,2], [:c], :d ]
  a.hashify.assoc  #=> { :a=>[1,2], :b=>[2], :c=>[], :d=>[] }

If the first entry of any subelements are the same, then the value will be set to the last occurring value.

  a = [ :x, [:x], [:x,1,2], [:x,3], [:x,4] ]
  a.hashify.assoc  #=> { :x=>[4] }

Converts enumerable object into a hash. Converting an array into a hash is not a one-to-one conversion, for this reason auto examines the enumerable being converted and then dispatches the conversion to the most suitable specialized function. There are three possibilities for this.

If the enumerable is a collection of perfect pairs, like that which Hash#to_a generates, then conversion is handled by flat.

  a = [ [:a,1], [:b,2] ]
  a.hashify.auto  #=> { :a=>1, :b=>2 }

If it contains only arrays, but are not perfect pairs, then multi is called.

  a = [ [:a,1,2], [:b,2], [:c], [:d] ]
  a.hashify.auto  #=> { :a=>[1,2], :b=>[2], :c=>[], :d=>[] }

If it contains objects other then arrays then the splat method is called.

  a = [ [:a,1,2], 2, :b, [:c,3], 9 ]
  a.hashify.auto  #=> { [:a,1,2]=>2, :b=>[:c,3], 9=>nil }

Be aware this is not as efficient as using the underlying methods directly because it must perform an initial iteration over the enumerable to determine its contents.

automatic(&block)

Alias for auto

Convert enumerable object to Hash using index as keys.

  [:a, :b, :c].hashify.by_index  #=> {1=>:a, 2=>:b, 3=>:c}

When a mixed or multi-element associative array is used, the result is as follows:

  a = [ [:a,1,2], [:b,2], [:c], :d ]
  a.hashify.concat  #=> { :a=>[1,2], :b=>[2], :c=>[], :d=>[] }

If the first entry of the subelements is the same, then the values will be merged using concat.

  a = [ [:a,1,2], [:a,3], [:a,4], [:a], :a ]
  a.hashify.concat  #=> { :a=>[1,2,3,4] }

This is equivalent to Hash, but it will pad the array with a nil object if there are not an even number of elements.

  a = [:a,1,[:b,2,:c]]
  a.to_h_flat  #=> { :a=>1, :b=>2, :c=>nil }

Like associate but does force values into an array.

multi()

Alias for concat

This is equivalent to Hash[*array], but it will pad the array with a nil object if there are not an even number of elements.

  a = [:a,1,:b,2,:c]
  a.to_h_splat  #=> { :a=>1, :b=>2, :c=>nil }

[Validate]