I’m currently trying to rexp a string into multiple variables. Example string:
ryan_string = "RyanOnRails: This is a test"
I’ve matched it with this regexp, with 3 groups:
ryan_group = ryan_string.scan(/(^.*)(:)(.*)/i)
Now to access each group I have to do something like this:
ryan_group[0][0] (first group) RyanOnRails
ryan_group[0][1] (second group) :
ryan_group[0][2] (third group) This is a test
This seems pretty ridiculous and it feels like I’m doing something wrong. I would be expect to be able to do something like this:
g1, g2, g3 = ryan_string.scan(/(^.*)(:)(.*)/i)
Is this possible? Or is there a better way than how I’m doing it?
You don’t want
scanfor this, as it makes little sense. You can useString#matchwhich will return aMatchDataobject, you can then call#capturesto return an Array of captures. Something like this:Be aware that if no match is found,
String#matchwill return nil, so something like this might work better:Although
scandoes make little sense for this. It does still do the job, you just need to flatten the returned Array first.one, two, three = string.scan(/(^.*)(:)(.*)/i).flatten