Skip to content

Fix Lazy#flat_map for non-enumerable block return values#6765

Merged
matz merged 2 commits intomruby:masterfrom
khasinski:fix-lazy-flat-map
Mar 29, 2026
Merged

Fix Lazy#flat_map for non-enumerable block return values#6765
matz merged 2 commits intomruby:masterfrom
khasinski:fix-lazy-flat-map

Conversation

@khasinski
Copy link
Copy Markdown
Contributor

Lazy#flat_map crashes with NoMethodError when the block returns a non-enumerable value, because it unconditionally calls #each on the result:

[1, 2, 3].lazy.flat_map {|x| x}.force
# mruby:  NoMethodError: undefined method 'each' for Integer
# CRuby:  [1, 2, 3]

CRuby handles this by checking whether the result responds to each -- if it does, iterate it; otherwise yield it directly. This PR matches that behavior and adds tests for arrays, non-enumerables, and nested arrays.

When the block passed to Lazy#flat_map returns a non-enumerable value
(e.g. an Integer), mruby raised NoMethodError because it unconditionally
called #each on the result. CRuby yields non-enumerable values directly.

Use respond_to?(:each) to match CRuby behavior: iterate enumerable
results, yield non-enumerable results as-is.
@khasinski khasinski requested a review from matz as a code owner March 28, 2026 21:59
Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request updates the implementation of Enumerator::Lazy#flat_map to handle block results that are not arrays by checking if the result responds to :each. It also adds new test cases to verify behavior with arrays, non-enumerable objects, and nested enumerables. A review comment suggests improving the clarity of the test descriptions to better distinguish between the different return types being tested.

@matz matz merged commit 801eefe into mruby:master Mar 29, 2026
19 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants