Sha256: 22d035c992001d89411ae09a3d22086f985cf886d3e1366993f411a401cce2bf

Contents?: true

Size: 542 Bytes

Versions: 3

Compression:

Stored size: 542 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

  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

3 entries across 3 versions & 1 rubygems

Version Path
bidu-core_ext-1.2.0 lib/enumerable.rb
bidu-core_ext-1.1.1 lib/enumerable.rb
bidu-core_ext-1.0.0 lib/enumerable.rb