Module: Darthjee::CoreExt::Hash::Transposeable

Included in:
Darthjee::CoreExt::Hash
Defined in:
lib/darthjee/core_ext/hash/transposeable.rb

Overview

Collection of methods for transposing keys and values of hash

Author:

  • darthjee

Instance Method Summary collapse

Instance Method Details

#transpose::Hash

Transpose matrix swapping keys by values

Examples:

hash = {
  key1: :value1,
  key2: :value2,
}

hash.transpose # changes hash to {
               #   value1: :key1,
               #   value2: :key2
               # }

Returns:



45
46
47
48
49
50
51
# File 'lib/darthjee/core_ext/hash/transposeable.rb', line 45

def transpose
  {}.tap do |new_hash|
    each do |key, value|
      new_hash[value] = key
    end
  end
end

#transpose!::Hash

Transpose matrix swapping keys by values

Examples:

hash = {
  key1: :value1,
  key2: :value2,
}

hash.transpose # returns {
               #   value1: :key1,
               #   value2: :key2
               # }

Returns:



25
26
27
28
29
# File 'lib/darthjee/core_ext/hash/transposeable.rb', line 25

def transpose!
  transposed = transpose
  keys.each(&method(:delete))
  merge!(transposed)
end