Project

General

Profile

Actions

Bug #18990

closed

Pattern matching unexpectedly raises "duplicated key name" error

Added by zeke (Zeke Gabrielse) over 1 year ago. Updated over 1 year ago.

Status:
Closed
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

Also available in: Atom PDF

Like0
Like0Like0Like0Like0