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

前端 未结 2 373
时光取名叫无心
时光取名叫无心 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>.)/
      $~[:name]
    else
    end
    
    0 讨论(0)
  • 2020-12-30 07:53

    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.

    0 讨论(0)
提交回复
热议问题