class HashMath::Unpivot
This class has the ability to extrapolate one hash (row) into multiple hashes (rows) while unpivoting specific keys into key-value pairs.
Attributes
pivot_set[R]
Public Class Methods
new(pivot_set = PivotSet.new)
click to toggle source
# File lib/hash_math/unpivot.rb, line 22 def initialize(pivot_set = PivotSet.new) @pivot_set = PivotSet.make(pivot_set, nullable: false) freeze end
Public Instance Methods
expand(hash)
click to toggle source
The main method for this class that performs the un-pivoting and hash expansion. Pass in a hash and it will return an array of hashes.
# File lib/hash_math/unpivot.rb, line 30 def expand(hash) return [hash] unless pivot_set.any? all_combinations = pivot_set.expand(hash) products = all_combinations.inject(all_combinations.shift) do |memo, array| memo.product(array) end recombine(products) end
Private Instance Methods
recombine(products)
click to toggle source
# File lib/hash_math/unpivot.rb, line 44 def recombine(products) products.map do |pairs| if pairs.is_a?(Array) pairs.inject(pairs.shift) { |memo, p| memo.merge(p) } else pairs end end end