Project

General

Profile

Actions

Bug #18990

closed

Pattern matching unexpectedly raises "duplicated key name" error

Added by zeke (Zeke Gabrielse) 3 months ago. Updated 3 months ago.

Status:
Closed
Priority:
Normal
Assignee:
-
Target version:
-
ruby -v:
ruby 3.1.2p20 (2022-04-12 revision 4491bb740a) [x86_64-darwin19]
[ruby-core:109813]

Description

I've found that sometimes, when matching nested patterns, I get an unexpected "duplicate key name" error but there's no duplicate key in any individual pattern. The "duplicated" key is actually in another pattern that's in scope, which I found was odd. (And the fix is even more odd.)

This seems like unexpected behavior to me. There's an example of this behavior below. The patterns in #all? cause the error, even though they're separate lines.

class User
  attr_reader :first_name,
              :last_name

  def initialize(first_name:, last_name:)
    @first_name, @last_name = first_name, last_name
  end

  def deconstruct_keys(keys)
    { first_name:, last_name: }
  end
end

users = [
  User.new(first_name: 'Jane', last_name: 'Doe'),
  User.new(first_name: 'Jane', last_name: 'Smith'),
]

# Fails
case users
in [{ first_name: 'John', ** }, *]
  users.all? { _1 in first_name: 'John' }
in [{ first_name: 'Jane', ** }, *]
  users.all? { _1 in first_name: 'Jane' } # => bug.rb:17: duplicated key name
end

Counterintuitively, wrapping the pattern in {} resolves the error.

# Works
case users
in [{ first_name: 'John', ** }, *]
  users.all? { _1 in { first_name: 'John' } }
in [{ first_name: 'Jane', ** }, *]
  users.all? { _1 in { first_name: 'Jane' } }
end

Seems like a bug?

Actions #1

Updated by ktsj (Kazuki Tsujimoto) 3 months ago

  • Status changed from Open to Closed

Applied in changeset git|db0e0dad1171456253ebd899e7e878823923d3d8.


Fix unexpected "duplicated key name" error in paren-less one line pattern matching

[Bug #18990]

Updated by ktsj (Kazuki Tsujimoto) 3 months ago

  • Backport changed from 2.7: UNKNOWN, 3.0: UNKNOWN, 3.1: UNKNOWN to 2.7: UNKNOWN, 3.0: UNKNOWN, 3.1: REQUIRED

@zeke (Zeke Gabrielse)
Thanks for reporting.

Actions #3

Updated by ktsj (Kazuki Tsujimoto) 3 months ago

  • Backport changed from 2.7: UNKNOWN, 3.0: UNKNOWN, 3.1: REQUIRED to 2.7: DONTNEED, 3.0: DONTNEED, 3.1: REQUIRED

Updated by nagachika (Tomoyuki Chikanaga) 3 months ago

  • Backport changed from 2.7: DONTNEED, 3.0: DONTNEED, 3.1: REQUIRED to 2.7: DONTNEED, 3.0: DONTNEED, 3.1: DONE

ruby_3_1 163947f4dc031bb5e619ae64ad4a6a02f8885717 merged revision(s) db0e0dad1171456253ebd899e7e878823923d3d8.

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0