Actions
Feature #14913
closedExtend case to match several values at once
Status:
Closed
Assignee:
-
Target version:
-
Description
This proposal is part of the search for how pattern matching or its elements could be gently introduced to Ruby.
This blog post (authored by me) provides context and "full" (more powerful than the current proposal, but more questionable also) idea, but I believe that this, more moderate, extension, could be a reasonable start.
Proposal:
Allow matching several values at once, when matching by case.
Example:
case (x, y)
when (0..10, 0..10)
...
when (Array, nil) # coordinates were passed as an array in first argument
...
when (Numeric, nil), (nil, Numeric) # somehow one of coordinates were missing
...
Justification:
- The syntax change is minimal (no new keywords/special chars), yet visible (very little possibility of hidden incompatibilities)
- It is alike deconstruction when passing arguments to methods or blocks
- It allows gradual adding of more features in the future versions of Ruby once the new syntax will become familiar:
case (x, *y) # flatten y
when (*Numeric) # match only an array of numerics
...
when (_, Array) # skip any
...
when (Numeric, Numeric => y, Hash => options) # match & assign, like in rescue
...
Links:
- Blog post with reasons, links to previous discussions and more examples
- Experimental gem to try as much of new proposals as possible to imitate in the current Ruby version.
PS:
Alternative syntax (reusing "block arguments" sign):
case |x, y|
when |0..10, 0..10|
...
when |Array, nil|
...
when |Numeric, nil|, |nil, Numeric| # OK, that's probably weird
...
Actions
Like0
Like0Like0Like0Like0Like0Like0