Module: Qo::Helpers

Included in:
Qo
Defined in:
lib/qo/helpers.rb

Instance Method Summary collapse

Instance Method Details

#count_by(targets, &fn) ⇒ Hash[Any, Integer]

Counts by a function. This is entirely because I hackney this everywhere in pry anyways, so I want a function to do it for me already.

Parameters:

  • targets (Array[Any])

    Targets to count

  • &fn (Proc)

    Function to define count key

Returns:

  • (Hash[Any, Integer])

    Counts



29
30
31
32
33
34
35
# File 'lib/qo/helpers.rb', line 29

def count_by(targets, &fn)
  fn ||= -> v { v }

  targets.each_with_object(Hash.new(0)) { |target, counts|
    counts[fn[target]] += 1
  }
end

#dig(path_map, expected_value) ⇒ Proc

Note:

This method will attempt to coerce path segments to Symbols if unsuccessful in first dig.

A curried variant of Hash#dig meant to be passed as a matcher util.

Parameters:

  • path_map (String)

    Dot-delimited path

  • expected_value (Any)

    Matcher

Returns:

  • (Proc)

    Hash -> Bool # Status of digging against the hash



13
14
15
16
17
18
19
20
# File 'lib/qo/helpers.rb', line 13

def dig(path_map, expected_value)
  Proc.new { |hash|
    segments = path_map.split('.')

    expected_value === hash.dig(*segments) ||
    expected_value === hash.dig(*segments.map(&:to_sym))
  }
end