Sha256: cdb4f88747142be32fff421098f2984253e578d5204d8275e9ba4c57a0dc007b

Contents?: true

Size: 780 Bytes

Versions: 15

Compression:

Stored size: 780 Bytes

Contents

module Enumerable
  def clean
    deep_dup.clean!
  end

  # delete hash or array values if value is nil
  # ex: { a: nil, b: 2 }.clean! => { b: 2 }
  def clean!
    if is_a?(Hash)
      delete_if { |_k, v| empty_value?(v) }
    else
      delete_if { |v| empty_value?(v) }
    end
  end

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

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

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

  private

  def empty_value?(v)
    v.nil? || v.try(:empty?) ||
      ((v.is_a?(Hash) || v.is_a?(Array)) && v.clean!.empty?)
  end
end

Version data entries

15 entries across 15 versions & 2 rubygems

Version Path
darthjee-core_ext-1.5.6 lib/darthjee/core_ext/enumerable.rb
darthjee-core_ext-1.5.5 lib/darthjee/core_ext/enumerable.rb
darthjee-core_ext-1.5.4 lib/darthjee/core_ext/enumerable.rb
darthjee-core_ext-1.5.3 lib/darthjee/core_ext/enumerable.rb
darthjee-core_ext-1.5.2 lib/darthjee/core_ext/enumerable.rb
darthjee-core_ext-1.5.1 lib/darthjee/core_ext/enumerable.rb
darthjee-core_ext-1.5.0 lib/darthjee/core_ext/enumerable.rb
darthjee-core_ext-1.4.1 lib/darthjee/core_ext/enumerable.rb
darthjee-core_ext-1.4.0 lib/darthjee/core_ext/enumerable.rb
darthjee-core_ext-1.3.1 lib/enumerable.rb
darthjee-core_ext-1.3.0 lib/enumerable.rb
darthjee-core_ext-1.2.6 lib/enumerable.rb
bidu-core_ext-1.2.5 lib/enumerable.rb
bidu-core_ext-1.2.4 lib/enumerable.rb
bidu-core_ext-1.2.3 lib/enumerable.rb