Class: Darthjee::CoreExt::Hash::KeysSorter Private

Inherits:
Object
  • Object
show all
Defined in:
lib/darthjee/core_ext/hash/keys_sorter.rb

Overview

This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.

Class responsible for sorting keys of a Hash

Author:

  • Darthjee

Instance Method Summary collapse

Constructor Details

#initialize(hash, recursive: true) ⇒ KeysSorter

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of KeysSorter.

Parameters:

  • hash (::hash)

    hash to be sorted

  • recursive (::TrueClass, ::FalseClass) (defaults to: true)

    flag indicating to perform transformation recursively



16
17
18
19
# File 'lib/darthjee/core_ext/hash/keys_sorter.rb', line 16

def initialize(hash, recursive: true)
  @hash = hash
  @recursive = recursive
end

Instance Method Details

#sort::Hash

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Creates a new Hash sorting it's keys

Examples:

Simple Usage

hash = { key: 10, a_key: { z: 5, a: 10 } }
sorter = Darthjee::CoreExt::Hash::KeysSorter.new(hash)

sorter.sort  # changes hash to {
             #   a_key: { a: 10, z: 5 },
             #   key: 10
             # }
hash = { b: 1, a: 2 }

hash.sort_keys  # returns { a: 2, b: 1 }

Returns:



35
36
37
38
39
40
41
# File 'lib/darthjee/core_ext/hash/keys_sorter.rb', line 35

def sort
  hash.tap do
    sorted_keys.each do |key|
      hash[key] = change_value(hash.delete(key))
    end
  end
end