Skip to content

Commit

Permalink
Allow omission of parentheses in one line pattern matching [Feature #…
Browse files Browse the repository at this point in the history
…16182]
  • Loading branch information
k-tsj committed Aug 19, 2021
1 parent 00d66f7 commit ecb6d6a
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 10 deletions.
8 changes: 7 additions & 1 deletion doc/syntax/pattern_matching.rdoc
Expand Up @@ -140,7 +140,7 @@ Both array and hash patterns support "rest" specification:
end
#=> "matched"

In +case+ (but not in <code>=></code> and +in+) expressions, parentheses around both kinds of patterns could be omitted:
Parentheses around both kinds of patterns could be omitted:

case [1, 2]
in Integer, Integer
Expand All @@ -158,6 +158,12 @@ In +case+ (but not in <code>=></code> and +in+) expressions, parentheses around
end
#=> "matched"

[1, 2] => a, b
[1, 2] in a, b

{a: 1, b: 2, c: 3} => a:
{a: 1, b: 2, c: 3} in a:

Find pattern is similar to array pattern but it can be used to check if the given object has any elements that match the pattern:

case ["a", 1, "b", "c", 2]
Expand Down
4 changes: 2 additions & 2 deletions parse.y
Expand Up @@ -1732,7 +1732,7 @@ expr : command_call
p->ctxt.in_kwarg = 1;
}
{$<tbl>$ = push_pvtbl(p);}
p_expr
p_top_expr_body
{pop_pvtbl(p, $<tbl>4);}
{
p->ctxt.in_kwarg = $<ctxt>3.in_kwarg;
Expand All @@ -1750,7 +1750,7 @@ expr : command_call
p->ctxt.in_kwarg = 1;
}
{$<tbl>$ = push_pvtbl(p);}
p_expr
p_top_expr_body
{pop_pvtbl(p, $<tbl>4);}
{
p->ctxt.in_kwarg = $<ctxt>3.in_kwarg;
Expand Down
11 changes: 11 additions & 0 deletions spec/ruby/language/pattern_matching_spec.rb
Expand Up @@ -1135,5 +1135,16 @@ def ===(obj)
result.should == true
end
end

ruby_version_is "3.1" do
it "can omit parentheses in one line pattern matching" do
[1, 2] => a, b
a.should == 1
b.should == 2

{a: 1} => a:
a.should == 1
end
end
end
end
14 changes: 7 additions & 7 deletions test/ruby/test_pattern_matching.rb
Expand Up @@ -1519,13 +1519,13 @@ def test_one_line
assert_raise(NoMatchingPatternError) do
{a: 1} => {a: 0}
end
assert_syntax_error("if {} => {a:}; end", /void value expression/)
assert_syntax_error(%q{
1 => a, b
}, /unexpected/, '[ruby-core:95098]')
assert_syntax_error(%q{
1 => a:
}, /unexpected/, '[ruby-core:95098]')
[1, 2] => a, b
assert_equal 1, a
assert_equal 2, b
{a: 1} => a:
assert_equal 1, a
assert_equal true, (1 in 1)
assert_equal false, (1 in 2)
Expand Down

0 comments on commit ecb6d6a

Please sign in to comment.