Puppet Function: stdlib::sort_by

Defined in:
lib/puppet/functions/stdlib/sort_by.rb
Function type:
Ruby 4.x API

Summary

Sort an Array, Hash or String by mapping values through a given block.

Overview

Examples:

Sort local devices according to their used space.

$facts['mountpoints'].stdlib::sort_by |$m| { $m.dig(1, 'used_bytes') }

Signatures:

  • stdlib::sort_by(Array $ary, Callable[1,1] &$block)Array

    Returns an ordered copy of ary.

    Parameters:

    • ary (Array)

      The Array to sort.

    • &block (Callable[1,1])

      The block for transforming elements of ary.

    Returns:

    • (Array)

      Returns an ordered copy of ary.

  • stdlib::sort_by(String $str, Callable[1,1] &$block)String

    Returns an ordered copy of str.

    Parameters:

    • str (String)

      The String to sort.

    • &block (Callable[1,1])

      The block for transforming elements of str.

    Returns:

    • (String)

      Returns an ordered copy of str.

  • stdlib::sort_by(Hash $hsh, Variant[Callable[1,1], Callable[2,2]] &$block)Hash

    Returns an ordered copy of hsh.

    Parameters:

    • hsh (Hash)

      The Hash to sort.

    • &block (Variant[Callable[1,1], Callable[2,2]])

      The block for transforming elements of hsh. The block may have arity of one or two.

    Returns:

    • (Hash)

      Returns an ordered copy of hsh.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/puppet/functions/stdlib/sort_by.rb', line 8

Puppet::Functions.create_function(:'stdlib::sort_by') do
  # @param ary The Array to sort.
  # @param block The block for transforming elements of ary.
  # @return [Array] Returns an ordered copy of ary.
  dispatch :sort_by_array do
    param 'Array', :ary
    block_param 'Callable[1,1]', :block
  end

  # @param str The String to sort.
  # @param block The block for transforming elements of str.
  # @return [String] Returns an ordered copy of str.
  dispatch :sort_by_string do
    param 'String', :str
    block_param 'Callable[1,1]', :block
  end

  # @param hsh The Hash to sort.
  # @param block The block for transforming elements of hsh.
  #              The block may have arity of one or two.
  # @return [Hash] Returns an ordered copy of hsh.
  dispatch :sort_by_hash do
    param 'Hash', :hsh
    block_param 'Variant[Callable[1,1], Callable[2,2]]', :block
  end

  def sort_by_iterable(iterable, &block)
    Puppet::Pops::Types::Iterable.asserted_iterable(self, iterable).sort_by(&block)
  end

  def sort_by_array(ary, &block)
    sort_by_iterable(ary, &block)
  end

  def sort_by_string(str, &block)
    sort_by_iterable(str, &block).join
  end

  def sort_by_hash(hsh, &block)
    sort_by_iterable(hsh, &block).to_h
  end
end