Module: Enumerable

Defined in:
lib/darthjee/core_ext/enumerable.rb

Instance Method Summary collapse

Instance Method Details

#cleanObject



4
5
6
# File 'lib/darthjee/core_ext/enumerable.rb', line 4

def clean
  deep_dup.clean!
end

#clean!Object

Removes any element that is nil or empty

Examples:

cleaning a Hash

hash = {
  keep: 'value',
  nil_value: nil,
  empty_array: [],
  empty_string: '',
  empty_hash: {}
}
hash.clean! # changes the hash to
            # { keep: 'value' }

cleaning an Array

array = ['value', nil, [], '', {}]
array.clean! # changes the array to be
             # ['value']


27
28
29
30
31
32
33
# File 'lib/darthjee/core_ext/enumerable.rb', line 27

def clean!
  if is_a?(Hash)
    delete_if { |_k, v| empty_value?(v) }
  else
    delete_if { |v| empty_value?(v) }
  end
end

#map_and_find {|*args| ... } ⇒ Object

Maps the elements into a new value, returning the first element that is evaluated to true

This method is equivalent to #map#find but only calling the map block up to when a value is found

Examples:

Using an array of keys to remove remove elements of a hash


service_map = {
  a: nil,
  b: false,
  c: 'found me',
  d: nil,
  e: 'didnt find me'
}

keys = %i[a b c d e]

keys.map_and_find { |key| service_values.delete(key) }
            # returns 'found me'
service_map # has lost only 3 keys returning
            # { d: nil, e: 'didnt find me' }

Yields:

  • (*args)

    mappig block



60
61
62
63
64
65
66
# File 'lib/darthjee/core_ext/enumerable.rb', line 60

def map_and_find
  mapped = nil
  find do |*args|
    mapped = yield(*args)
  end
  mapped || nil
end

#map_and_select {|*args| ... } ⇒ Object

Maps the elements into a new value returning an array of the values mapped to non false values

This method is equivalent to call #map#select

Examples:

Mapping the values of hash to their size

hash = {
  a: nil,
  b: 'aka',
  c: 'a'
}

values = hash.map_and_select do |key, value|
  value && value.to_s
end

values # returns [3, 1]

Yields:

  • (*args)

    mapping block



87
88
89
90
91
92
# File 'lib/darthjee/core_ext/enumerable.rb', line 87

def map_and_select
  mapped = map do |*args|
    yield(*args)
  end
  mapped.select { |e| e }
end

#map_to_hash {|*args| ... } ⇒ Object

Maps values and creates a hash whose values are the result of the #map and the keys are the original values

Examples:

Mapping strings to their sizes

strings =  %w[word big_word]

strings.map_to_hash(&:size) # returns { 'word' => 4, 'big_word' => 8 }

Yields:

  • (*args)

    the mapping block



103
104
105
106
107
108
109
# File 'lib/darthjee/core_ext/enumerable.rb', line 103

def map_to_hash
  {}.tap do |hash|
    each do |element|
      hash[element] = yield(element)
    end
  end
end