Sha256: 58a466ec9b6bd8debb3e4de253d2f487aa1d35be72fed486d7df079f163fd6a6

Contents?: true

Size: 753 Bytes

Versions: 35

Compression:

Stored size: 753 Bytes

Contents

# A decorator for handling a collection of hashes with similar keys.
#
class HashCollection < SimpleDelegator
  alias_method :collection, :__getobj__

  # Example:
  #
  #   foo = [
  #     {a: 1, b: 2},
  #     {b: 3, c: 4}
  #   ]
  #
  #   bar = HashCollection.new(foo)
  #   bar.to_a => [[:a, 1, nil], [:b, 2, 3], [:c, nil, 4]]
  #
  def to_a
    keys = find_unique_keys
    build_items(keys)
  end

  private

  def find_unique_keys
    collection.flat_map(&:keys).uniq
  end

  def build_items(keys)
    keys.each_with_object([]) do |key, memo|
      memo << build_item_for_key(key)
    end
  end

  def build_item_for_key(key)
    [key] + find_values(key)
  end

  def find_values(key)
    collection.map { |result| result.fetch(key) }
  end
end

Version data entries

35 entries across 35 versions & 1 rubygems

Version Path
renalware-core-2.0.16 lib/hash_collection.rb
renalware-core-2.0.15 lib/hash_collection.rb
renalware-core-2.0.14 lib/hash_collection.rb
renalware-core-2.0.13 lib/hash_collection.rb
renalware-core-2.0.12 lib/hash_collection.rb
renalware-core-2.0.11 lib/hash_collection.rb
renalware-core-2.0.9 lib/hash_collection.rb
renalware-core-2.0.8 lib/hash_collection.rb
renalware-core-2.0.7 lib/hash_collection.rb
renalware-core-2.0.5 lib/hash_collection.rb
renalware-core-2.0.4 lib/hash_collection.rb
renalware-core-2.0.3 lib/hash_collection.rb
renalware-core-2.0.2 lib/hash_collection.rb
renalware-core-2.0.1 lib/hash_collection.rb
renalware-core-2.0.0 lib/hash_collection.rb
renalware-core-2.0.0.pre.rc13 lib/hash_collection.rb
renalware-core-2.0.0.pre.rc11 lib/hash_collection.rb
renalware-core-2.0.0.pre.rc10 lib/hash_collection.rb
renalware-core-2.0.0.pre.rc9 lib/hash_collection.rb
renalware-core-2.0.0.pre.rc8 lib/hash_collection.rb