Module: Transproc::ArrayTransformations

Extended by:
Functions
Defined in:
lib/transproc/array.rb

Overview

Transformation functions for Array objects

Examples:

require 'transproc/array'

include Transproc::Helper

fn = t(:map_array, t(:symbolize_keys)) >> t(:wrap, :address, [:city, :zipcode])

fn.call(
  [
    { 'city' => 'Boston', 'zipcode' => '123' },
    { 'city' => 'NYC', 'zipcode' => '312' }
  ]
)
# => [{ city: 'Boston', zipcode: '123' }, { city: 'NYC', zipcode: '312' }]

Instance Method Summary collapse

Methods included from Functions

method_added

Instance Method Details

#group(array, key, keys) ⇒ Array

Group array values using provided root key and value keys

Examples:

fn = Transproc(:group, :tags, [:tag_name])

fn.call [
  { task: 'Group it', tag: 'task' },
  { task: 'Group it', tag: 'important' }
]
# => [{ task: 'Group it', tags: [{ tag: 'task' }, { tag: 'important' }]]

Parameters:

  • array (Array)

    The input array

  • key (Object)

    The nesting root key

  • keys (Object)

    The nesting value keys

Returns:

  • (Array)


89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/transproc/array.rb', line 89

def group(array, key, keys)
  grouped = Hash.new { |h, k| h[k] = [] }
  array.each do |hash|
    hash = hash.dup
    child = {}
    keys.each { |k| child[k] = hash.delete(k) }
    grouped[hash] << child
  end
  grouped.map do |root, children|
    root.merge(key => children)
  end
end

#map_array(array, fn) ⇒ Array

Map array values using transformation function

Examples:


fn = Transproc(:map_array, -> v { v.upcase })

fn.call ['foo', 'bar'] # => ["FOO", "BAR"]

Parameters:

  • array (Array)

    The input array

  • fn (Proc)

    The transformation function

Returns:

  • (Array)


39
40
41
# File 'lib/transproc/array.rb', line 39

def map_array(array, fn)
  map_array!(Array[*array], fn)
end

#map_array!(array, fn) ⇒ Object

Same as ‘map_array` but mutates the array

See Also:



48
49
50
# File 'lib/transproc/array.rb', line 48

def map_array!(array, fn)
  array.map! { |value| fn[value] }
end

#wrap(array, key, keys) ⇒ Array

Wrap array values using HashTransformations.nest function

Examples:

fn = Transproc(:wrap, :address, [:city, :zipcode])

fn.call [{ city: 'NYC', zipcode: '123' }]
# => [{ address: { city: 'NYC', zipcode: '123' } }]

Parameters:

  • array (Array)

    The input array

  • key (Object)

    The nesting root key

  • keys (Object)

    The nesting value keys

Returns:

  • (Array)


67
68
69
# File 'lib/transproc/array.rb', line 67

def wrap(array, key, keys)
  map_array(array, Transproc(:nest, key, keys))
end