Feature #15865


`<expr> in <pattern>` expression

Added by mame (Yusuke Endoh) over 2 years ago. Updated about 2 years ago.

Target version:


How about adding a syntax for one-line pattern matching: <expr> in <pattern> ?

[1, 2, 3] in x, y, z #=> true (with assigning 1 to x, 2 to y, and 3 to z)
[1, 2, 3] in 1, 2, 4 #=> false

More realistic example:

json = {
  name: "ko1",
  age: 39,
  address: { postal: 123, city: "Taito-ku" }

if json in { name:, age: (20..), address: { city: "Taito-ku" } }
  p name #=> "ko1"
  raise "wrong format"

It is simpler and more composable than "" when only one "in" clause is needed. I think that in Ruby a pattern matching would be often used for "format-checking", to check a structure of data, and this use case would usually require only one clause. This is the main rationale for the syntax I propose.

Additional two small rationales:

  • It may be used as a kind of "right assignment": 1 + 1 in x behaves like x = 1 + 1. It returns true instead of 2, though.
  • There are some arguments about the syntax "". But if we have <expr> in <pattern>, "" can be considered as a syntactic sugar that is useful for multiple-clause cases, and looks more natural to me.

There are two points I should note:

  • <expr> in <pattern> is an expression like <expr> and <expr>, so we cannot write it as an argument: foo(1 in 1) causes SyntaxError. You need to write foo((1 in 1)) as like foo((1 and 1)). I think it is impossible to implement.
  • Incomplete pattern matching also rewrites variables: [1, 2, 3] in x, 42, z will write 1 to the variable "x". This behavior is the same as the current "".

Nobu wrote a patch:

Related issues

Related to Ruby master - Feature #14912: Introduce pattern matching syntaxClosedktsj (Kazuki Tsujimoto)Actions
Related to Ruby master - Feature #16182: Should `expr in a, b, c` be allowed or not?Closedmatz (Yukihiro Matsumoto)Actions
Related to Ruby master - Feature #16355: Raise NoMatchingPatternError when `expr in pat` doesn't matchClosedActions
Related to Ruby master - Feature #17371: Reintroduce `expr in pat`ClosedActions

Also available in: Atom PDF