Permalink
Browse files

Enumerable#build_hash: nil return from block signals skip

  • Loading branch information...
quix committed Aug 9, 2009
1 parent 36efbdb commit 40c091e28b3015a7ced7905b2fd72b110fb38f29
Showing with 30 additions and 4 deletions.
  1. +13 −3 lib/quix/ext/enumerable.rb
  2. +17 −1 test/enumerable_test.rb
View
@@ -16,11 +16,21 @@ def group_consecutive_by
result
end
+ #
+ # build_hash appears in Gavin Sinclair's extensions package.
+ #
+ # This implementation is slightly different in that it skips yield
+ # results of nil.
+ #
def build_hash
- inject(Hash.new) { |acc, elem|
- result = yield(elem)
- acc.merge!(result[0] => result[1])
+ result = Hash.new
+ each { |elem|
+ pair = yield(elem)
+ unless pair.nil?
+ result[pair[0]] = pair[1]
+ end
}
+ result
end
def take_until(&block)
View
@@ -17,7 +17,7 @@ def test_group_consecutive_by
assert_equal expected, computed
end
- def test_build_hash
+ def test_build_hash_1
data = 3..5
expected = {
3 => 9,
@@ -30,6 +30,22 @@ def test_build_hash
assert_equal expected, computed
end
+ def test_build_hash_2
+ data = 3..5
+ expected = {
+ 3 => 9,
+ 5 => 25
+ }
+ computed = data.build_hash { |elem|
+ if elem == 4
+ nil
+ else
+ [elem, elem**2]
+ end
+ }
+ assert_equal expected, computed
+ end
+
def test_take_drop
data = 3..8

0 comments on commit 40c091e

Please sign in to comment.