The
string.split method partitions into elements according to the specified separator.
Consider a comma separated file (CSV) which you for example can open with Excel and it splits the elements in a line neatly into different rows. It does not take the actual commas along. This is analogous with how the string split method works. The separator is not added to elements in the array. Now instead of a specific character we define separator by a regular expression where Yanfly uses
[\r\n]+First step to understanding the different between the two lines is to understand what the regular expression matches. A good heuristic is to decompose to the simplest entities and build up.
We have [ ] with the meaning of (any character in the set). If we for example have /[ab]/ then it is equivalent to /a|b/.
There are two possible matches "a" and "b".
The + means 1 or more repetitions. /a+/ matches "a", "aa", "aaa", ...
Since the [] is treated as a single entity for the + we have that /[ab]+/ matches for example "abbaba", "baab" and "a".
Substitute
a and
b with
\n and
\r to get Yanfly's equation.
We can now easily see that a separator is defined as any non-empty substring containing only line feed and carriage return characters.
Compare with your line where a separator is a single line feed.
Including the carriage return is considered good practice because you would then cover both the Windows and Unix cases.
The important part, however, is considering a separator to be specifically one line feed character.
This is important because of the way the string.split method treats separators.
Try to figure it out on your own how it works. When you feel ready, try to guess what the following code will output before running it:
str = "Test 1\nTest 2\r\n\n\n\r\n5\n\r642345\n2gj"
arr1 = []
arr2 = []
str.split(/[\r\n]+/).each do |line|
arr1 << line
end
str.split(/\n/).each do |line|
arr2 << line
end
str1 = arr1.join
str2 = arr2.join
p str, str1, str2, arr1, arr2
#msgbox_p str, str1, str2, arr1, arr2 # Use if run in VX Ace
exit
Remember that one is not necessarily better than the other. Not in general. Which to pick depends on your specific context.
*hugs*
- Zeriab