Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 292
Chris Avatar asked Mar 09 '12 22:03

Chris


1 Answers

named captures set local variables when this syntax.

regex-literal =~ string

Dosen'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
like image 92
kachick Avatar answered Oct 02 '22 23:10

kachick