Class: Goldmine::ArrayMiner

Inherits:
SimpleDelegator
  • Object
show all
Defined in:
lib/goldmine/array_miner.rb

Instance Method Summary collapse

Constructor Details

#initialize(array = []) ⇒ ArrayMiner

Returns a new instance of ArrayMiner.



6
7
8
# File 'lib/goldmine/array_miner.rb', line 6

def initialize(array=[])
  super array
end

Instance Method Details

#pivot(name = nil) {|Object| ... } ⇒ Hash

Pivots the Array into a Hash of mined data. Think of it as creating a pivot table or perhaps an OLAP cube.

Examples:

Simple pivot

list = [1,2,3,4,5,6,7,8,9]
data = list.pivot { |i| i < 5 }

# resulting data
# {
#   true  => [1, 2, 3, 4],
#   false => [5, 6, 7, 8, 9]
# }

Named pivot

list = [1,2,3,4,5,6,7,8,9]
data = list.pivot("less than 5") { |i| i < 5 }

# resulting data
# {
#   { "less than 5" => true } => [1, 2, 3, 4],
#   { "less than 5" => false } => [5, 6, 7, 8, 9]
# }

Chained pivot

list = [1,2,3,4,5,6,7,8,9]
data = list.pivot { |i| i < 5 }.pivot { |i| i % 2 == 0 }

# resulting data
{
  [true, false]  => [1, 3],
  [true, true]   => [2, 4],
  [false, false] => [5, 7, 9],
  [false, true]  => [6, 8]
}

Parameters:

  • name (String) (defaults to: nil)

    The named of the pivot.

Yields:

  • (Object)

    Yields once for each item in the Array

Returns:

  • (Hash)

    The pivoted Hash of data.



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/goldmine/array_miner.rb', line 48

def pivot(name=nil, &block)
  reduce(HashMiner.new) do |memo, item|
    value = yield(item)

    if value.is_a?(Array)
      if value.empty?
        memo.assign_mined(name, nil, item)
      else
        value.each { |v| memo.assign_mined(name, v, item) }
      end
    else
      memo.assign_mined(name, value, item)
    end

    memo.goldmine = true
    memo
  end
end