13

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
Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
Chris
  • 11,819
  • 19
  • 91
  • 145
  • I do not think this is possible in such a clever manner. However, the "magic capture variable" (`$n`) should still be available... I'm not sure why the -1 :( –  Mar 09 '12 at 22:49
  • 1
    Yeah I could use $1 but Ruby is great for its readability, I'm not looking to go back to Perl. Haha I'm not worried about losing made up points. – Chris Mar 09 '12 at 22:54

2 Answers2

14

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
kachick
  • 371
  • 2
  • 7
7

This is ugly but works for me in Ruby 1.9.3:

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

Alternatively you can use the English extension of $~, $LAST_MATCH_INFO.

Gabe Kopley
  • 16,281
  • 5
  • 47
  • 60