mirror of
https://github.com/mruby/mruby
synced 2026-06-08 16:11:16 +00:00
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:
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user