mruby-enum-lazy: add Enumerator::Lazy#tap_each

add tap_each method that yields each element for side effects
(e.g. logging, debugging) and passes it through unmodified.
see https://bugs.ruby-lang.org/issues/21520

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
Yukihiro "Matz" Matsumoto
2026-03-18 09:58:20 +09:00
parent d2caa144be
commit f3cd991771
2 changed files with 33 additions and 0 deletions
+20
View File
@@ -349,6 +349,26 @@ class Enumerator
}
end
#
# call-seq:
# lazy.tap_each {|obj| block } -> lazy_enumerator
#
# Yields each element to the block for side effects (e.g. logging,
# debugging) and passes it through unmodified.
#
# (1..Float::INFINITY).lazy
# .tap_each {|i| puts "saw: #{i}" }
# .select(&:even?)
# .first(3)
# #=> [2, 4, 6] (prints "saw: 1", "saw: 2", ... along the way)
#
def tap_each(&block)
Lazy.new(self){|yielder, val|
block.call(val)
yielder << val
}
end
#
# call-seq:
# lazy.force -> array
+13
View File
@@ -64,6 +64,19 @@ assert("Enumerator::Lazy#grep_v") do
assert_equal [0, 1, 5, 6], lazy_grep_v.first(4)
end
assert("Enumerator::Lazy#tap_each") do
seen = []
result = [1, 2, 3, 4, 5].lazy.tap_each{|x| seen << x }.select{|x| x % 2 == 0 }.force
assert_equal [2, 4], result
assert_equal [1, 2, 3, 4, 5], seen
end
assert("Enumerator::Lazy#tap_each laziness") do
seen = []
[1, 2, 3, 4, 5].lazy.tap_each{|x| seen << x }.first(3)
assert_equal [1, 2, 3], seen
end
assert("Enumerator::Lazy#zip with cycle") do
e1 = [1, 2, 3].cycle
e2 = [:a, :b].cycle