Syntax: special handling of tuple condition in case expression #2258
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This is a follow up of #2239
Thanks to suggestions from @kostya and @ysbaddaden, I changed the proposed syntax from this:
To this:
As you can see, that syntax is already supported by the current compiler, so the compiler is just updated to rewrite the code in a few special cases. Specifically, if the case condition is a tuple literal, then:
{
), then the "implicit object" notation is allowed in its members (for example{.even?, .odd?}
)case {x, y}; when {Int32, Float64}
is rewritten toif x.is_a?(Int32) && y.is_a?(Float64)
, allowing type filters to work, something that doesn't work right now (this is the main motivation for adding this funcionality).===
is used. For this to work, I addedTuple#===
, which was missing.With this, we can finally solve real world problems like fizzbuzz in an elegant way:
Of, if you want
{0, 0}
as a constant, you can do it too:Another advantage of this syntax is that it allows multiple when conditions, for example: