Ruby Regexp group matching, assign variables on 1 line

前端 未结 5 845
旧巷少年郎
旧巷少年郎 2020-12-07 12:38

I\'m currently trying to rexp a string into multiple variables. Example string:

ryan_string = \"RyanOnRails: This is a test\"

I\'ve mat

5条回答
  •  -上瘾入骨i
    2020-12-07 13:21

    You have to decide whether it is a good idea, but ruby regexp can (automagically) define local variables for you!

    I am not yet sure whether this feature is awesome or just totally crazy, but your regex can define local variables.

    ryan_string = "RyanOnRails: This is a test"
    /^(?.*)(?:)(?)/ =~ ryan_string
    # This defined three variables for you. Crazy, but true.
    webframework # => "RyanOnRails"
    puts "W: #{webframework} , C: #{colon}, R: #{rest}"
    

    (Take a look at http://ruby-doc.org/core-2.1.1/Regexp.html , search for "local variable").

    Note: As pointed out in a comment, I see that there is a similar and earlier answer to this question by @toonsend (https://stackoverflow.com/a/21412455). I do not think I was "stealing", but if you want to be fair with praises and honor the first answer, feel free :) I hope no animals were harmed.

提交回复
热议问题