Sha256: e203495111a45d712c08cbdb05cde188d2a82db950ae341ce076709af237b327

Contents?: true

Size: 779 Bytes

Versions: 10

Compression:

Stored size: 779 Bytes

Contents

module Enumerable

  # Like #group_by, but maps the second value returned from the block.
  #
  #   a = [1,2,3,4,5]
  #   a.map_by{ |e| [e % 2, e + 1] }
  #   #=> { 0=>[3,5], 1=>[2,4,6] }
  #
  # Works well with a hash too.
  #
  #   h = {"A"=>1, "B"=>1, "C"=>1, "D"=>2, "E"=>2}
  #   h.map_by{ |k,v| [v, k.downcase] }
  #   #=> {1=>["a", "b", "c"], 2=>["d", "e"]}
  #
  # If a second value is not returned, #map_by acts like #group_by.
  #
  #   h = {"A"=>1, "B"=>1, "C"=>1, "D"=>2, "E"=>2}
  #   h.map_by{ |k,v| v }
  #   #=> {1=>[["A",1], ["B",1], ["C",1]], 2=>[["D",2], ["E",2]]}
  #
  def map_by #:yield:
    res = {}
    each do |a|
      k,v = yield(*a)
      if v
        (res[k] ||= []) << v
      else
        (res[k] ||= []) << a
      end
    end
    res
  end

end

Version data entries

10 entries across 9 versions & 2 rubygems

Version Path
facets-glimmer-3.2.0 lib/core/facets/enumerable/map_by.rb
facets-3.1.0 lib/core/facets/enumerable/map_by.rb
facets-3.0.0 lib/core/facets/enumerable/map_by.rb
facets-2.9.3 lib/core/facets/enumerable/map_by.rb
facets-2.9.2 lib/core/facets/enumerable/map_by.rb
facets-2.9.2 src/core/facets/enumerable/map_by.rb
facets-2.9.1 lib/core/facets/enumerable/map_by.rb
facets-2.9.0 lib/core/facets/enumerable/map_by.rb
facets-2.9.0.pre.2 lib/core/facets/enumerable/map_by.rb
facets-2.9.0.pre.1 lib/core/facets/enumerable/map_by.rb