What does splat do here?

match, text, number = *"foobar 123".match(/([A-z]*) ([0-9]*)/)

I know this makes some kind of regular expression, but what role does splat play here, and is there a way to do this without splat so that it is less confusing?

+3
source share
5 answers

Is there a way to do this without splat so that it is less confusing?

Since it a,b = [c,d]matches a,b = *[c,d]and splat calls to_aon its operand when it is not an array, you can just call to_a explicitly and not need a sign:

match, text, number = "foobar 123".match(/([A-z]*) ([0-9]*)/).to_a

I do not know if it is not less confusing, but it is free.

+3
source

(a MatchData : , ) . , :

match = "foobar 123"
text = "foobar"
number = "123"

splat (MatchData), Ruby , .

+5

MatchData:

to_a * , . , ( ).

   all,f1,f2,f3 = *(/(.)(.)(\d+)(\d)/.match("THX1138."))
   all   #=> "HX1138"
   f1    #=> "H"
   f2    #=> "X"
   f3    #=> "113"
+3

String.match returns a MatchData object that contains all regular expression matches. The splat operator splits this object and returns all matches separately.

If you just run

"foobar 123".match(/([A-z]*) ([0-9]*)/)

in irb, you can see the MatchData object with collected matches.

0
source

MatchData is a special variable, for all purposes and tasks - an array (view), so you really can do this:

match, text, number = "foobar 123".match(/([A-z]*) ([0-9]*)/)[0..2]

Learn more about the MatchData special variable.

0
source

Source: https://habr.com/ru/post/1718215/


All Articles