Class: MultiHash
- Inherits:
-
Object
- Object
- MultiHash
- Defined in:
- lib/multi_hash_iterator.rb
Overview
Multi Hash allows you to iterate through multiple hashes at the same time. The values will be an array of values from each hash. If a hash contains no value for the key, it will be nil.
Instance Method Summary collapse
- #[](key) ⇒ Object
-
#each ⇒ Object
Enumerate for each key.
-
#initialize(*hashes) ⇒ MultiHash
constructor
A new instance of MultiHash.
Constructor Details
#initialize(*hashes) ⇒ MultiHash
Returns a new instance of MultiHash.
7 8 9 10 |
# File 'lib/multi_hash_iterator.rb', line 7 def initialize *hashes @hashes = hashes @memo = {} end |
Instance Method Details
#[](key) ⇒ Object
41 42 43 |
# File 'lib/multi_hash_iterator.rb', line 41 def [] key @memo[key] ||= @hashes.collect { |h| h[key] } end |
#each ⇒ Object
Enumerate for each key. Returns an enumerator if block is not present
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/multi_hash_iterator.rb', line 15 def each return enum_for(:each) unless block_given? # iterate through the memo first @memo.each do |k, v| yield k, v end count = @hashes.length count.times do |i| @hashes[i].each do |key, v| next if @memo[key] values = [].fill(nil, 0, i) values << v ((i+1)...count).each do |j| values << @hashes[j][key] end yield key, values if block_given? @memo[key] = values end end end |