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

前端 未结 2 372
时光取名叫无心
时光取名叫无心 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: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 (?\w+)/
        load($~[:filename])
      end
    end
    

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

提交回复
热议问题