rubyregexswitch-statementcapture

Using Named Captures with regex match in Ruby's case...when?


I want to parse user input using named captures for readability.

When they type a command I want to capture some params and pass them. I'm using RegExps in a case statement and thus I can't assign the return of /pattern/.named_captures.

Here is what I would like to be able to do (for example):

while command != "quit"
  print "Command: "
  command = gets.chomp
  case command
  when /load (?<filename>\w+)/
    load(filename)
  end
end

Solution

  • Named captures set local variables when this syntax.

    regex-literal =~ string
    

    Doesn't set in other syntax. # See rdoc(re.c)

    regex-variable =~ string
    
    string =~ regex
    
    regex.match(string)
    
    case string
    when regex
    else
    end
    

    I like named captures too, but I don't like this behavior. Now, we have to use $~ in case syntax.

    case string
    when /(?<name>.)/
      $~[:name]
    else
    end