From: "marcandre (Marc-Andre Lafortune) via ruby-core" <ruby-core@...>
Date: 2023-05-18T04:28:45+00:00
Subject: [ruby-core:113510] [Ruby master Feature#19634] Pattern matching dynamic key

Issue #19634 has been updated by marcandre (Marc-Andre Lafortune).


FWIW, Elixir actually supports it, but I've not seen it used in the wild

``` elixir
map = %{mentor_name: "Joe"}
value = "Joe"
key = :mentor_name
match?(%{^key => ^value}, map) # => true

```


----------------------------------------
Feature #19634: Pattern matching dynamic key
https://bugs.ruby-lang.org/issues/19634#change-103137

* Author: baweaver (Brandon Weaver)
* Status: Open
* Priority: Normal
----------------------------------------
I found myself in a situation ([stable marriage problem](https://rosettacode.org/wiki/Stable_marriage_problem#top-page)) where I would like to match against a dynamic key, like so:

```ruby
mentor_proposals = { mentor_name: ['mentee_1', 'mentee_2'] }
mentor_name = :mentor_name
mentee_name = 'mentee_1'

mentor_proposals in ^key: [*, ^mentee_name, *] # SyntaxError
```

Currently this is not supported syntax, but there are some use cases in which I might see myself wanting to use it including this one. As `deconstruct_keys` currently accepts an `Array` of keys this would not break compatibility but would introduce syntactic complexity in capturing keys on hash-like matches.

I believe the tradeoff is worthwhile, but would like to hear others opinions on the matter.

Granted this case has some oddities of `Symbol` and `String` interchangeability as an implementation detail, and I will not be arguing for key irreverence in this issue as that's a [much more involved topic](https://dev.to/baweaver/the-case-for-pattern-matching-key-irreverence-in-ruby-1oll).



-- 
https://bugs.ruby-lang.org/
 ______________________________________________
 ruby-core mailing list -- ruby-core@ml.ruby-lang.org
 To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org
 ruby-core info -- https://ml.ruby-lang.org/mailman3/postorius/lists/ruby-core.ml.ruby-lang.org/