Possible Duplicate:
Using Named Captures with regex match in Ruby’s case…when?
I'm trying to use named groups (capture groups with a name supplied) more often, to make my code more readable.
I'm trying to work out how to do that for a case
statement:
date_field = "Wk 9"
date = case date_field
when /^Wk (?<weeks>\d+)$/ then 7 * Integer(weeks)
else raise "Unexpected date_field #{date_field.inspect}"
end
gives me
NameError: undefined local variable or method `weeks' for main:Object
unlike
date_field = "Wk 9"
/^Wk (?<weeks>\d+)$/ =~ date_field
date = 7 * Integer(weeks)
date # => 63
Is there any way of doing a named group from a case statement?
Most similar question I could find: How to write a Ruby switch statement (case...when) with regex and backreferences? , but the accepted answer only talks about using $1
to $9
.