Sha256: 556add49646ecb051b0ddf4f5252186daa4d8962cbacce4e4cabab5f04dcf3af

Contents?: true

Size: 1004 Bytes

Versions: 1

Compression:

Stored size: 1004 Bytes

Contents

#--
# Credit goes to Florian Gross.
#++
require 'nano/enumerable/filter_collect'

module Enumerable

  # Collects/Maps and compacts items in one single step.
  # The items for which the supplied block returns +nil+ will not
  # end up in the resulting array.
  #
  #   # Return telephone numbers of all persons that have a telephone number.
  #   persons.compact_collect { |person| person.telephone_no }
  #
  # Also see Enumerable#collect, Enumerable#map, Array#compact.
  #
  def compact_collect #:yield:
    filter_collect do |item|
      new_item = yield(item)
      throw(:skip) if new_item.nil?
      new_item
    end
  end

  alias_method :compact_map, :compact_collect

end



#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TCEnumerable < Test::Unit::TestCase

    def test_compact_collect
      a = [1,2,nil,4].compact_collect { |e| e }
      assert_equal( [1,2,4], a )
    end

  end

=end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
facets-0.9.0 lib/nano/enumerable/compact_collect.rb