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

前端 未结 2 377
时光取名叫无心
时光取名叫无心 2020-12-30 07:27

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 s

2条回答
  •  别那么骄傲
    2020-12-30 07:38

    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]
    else
    end
    

提交回复
热议问题