From: milouse Date: 2022-11-14T09:52:50+00:00 Subject: [ruby-core:110747] [Ruby master Feature#16796] Assigning local variables when using `case when regexp` Issue #16796 has been updated by milouse (��tienne Deparis). shyouhei (Shyouhei Urabe) wrote in #note-3: > sawa (Tsuyoshi Sawada) wrote in #note-2: > > That's too confusing. The following code works today. > > ```ruby > case "str" > in /s(.)r/ => match_data > match_data[1] # => "t" > end > ``` Not really (or at least it is not what I understand from the original request, as I felt on a similar issue today). You are just pointing out an edge case where `match_data[1]` will be `t`, not because it is actually a `MatchData` object, which first capturing group worth `t`, but just because the pattern matching feature select this branch and put the original `String` "str" onto `match_data`. Thus `match_data[1]` here only gives you the second char of the string `match_data`. The previous example would have fail (in my understanding of the problem), with the following regexp: ```ruby case "str" in /(.)tr/ => match_data match_data[1] # => "t" instead of the expected "s" end ``` By the way, there is in fact a very simple way to achieve the initial goal (again, from my understanding of the problem): ``` case "str" when /s(?.)r/ match_data = Regexp.last_match p match_data[:mid] end ``` ---------------------------------------- Feature #16796: Assigning local variables when using `case when regexp` https://bugs.ruby-lang.org/issues/16796#change-100084 * Author: UlyssesZhan (Ulysses Zhan) * Status: Rejected * Priority: Normal ---------------------------------------- I want to use ```ruby case "str" when /s(?.)r/ p mid end ``` instead of ```ruby case when /s(?.)r/ =~ "str" p mid end ``` I also do not like using `$1`. This feature is extremely useful when there are a lot of `when`s. -- https://bugs.ruby-lang.org/ Unsubscribe: