Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/hash-zip.rb

Overview

Enumerable#zip is nonsense when applied to Hashes

Instance Method Summary collapse

Instance Method Details

#zip(*args) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/hash-zip.rb', line 3

def zip(*args)
  sources = [self]
  args.each do |arg|
    if arg.is_a?(Hash)
      sources << arg
    else
      sources << arg.to_h
    end
  end
  output_keys = sources.flat_map(&:keys).uniq
  if block_given?
    output_keys.each do |key|
      yield(key, *sources.map{|source| source[key]})
    end
    nil
  else
    result = {}
    output_keys.each do |key|
      result[key] = sources.map{|source| source[key]}
    end
    result
  end
end