Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String#split strange behavior [duplicate]

Tags:

ruby

I observed a strange behavior of the split method on a String.

"1..2".split('..')      # => ['1', '2']
"1..2".split('..', 2)   # => ['1', '2']

"..2".split('..')       # => ['', '2']
"..2".split('..', 2)    # => ['', '2']

Everything like expected, but now:

"1..".split('..')       # => ['1']
"1..".split('..', 2)    # => ['1', '']

I would expect the first to return the same that the second.

Does anyone have a good explanation, why "1..".split('..') returns an array with just one element? Or is it an inconsistency in Ruby? What do you think about that?

like image 323
spickermann Avatar asked Aug 31 '25 03:08

spickermann


1 Answers

According to the Ruby String documentation for split:

If the limit parameter is omitted, trailing null fields are suppressed.

Regarding the limit parameter, the Ruby documentation isn't totally complete. Here is a little more detail:

  • If limit is positive, split returns at most that number of fields. The last element of the returned array is the "rest of the string", or a single null string ("") if there are fewer fields than limit and there's a trailing delimiter in the original string.

Examples:

"2_3_4_".split('_',3)
=> ["2", "3", "4_"]

"2_3_4_".split('_',4)
=> ["2", "3", "4", ""]
  • If limit is zero [not mentioned in the documentation], split appears to return all of the parsed fields, and no trailing null string ("") element if there is a trailing delimiter in the original string. I.e., it behaves as if limit were not present. (It may be implemented as a default value.)

Example:

"2_3_4_".split('_',0)
=> ["2", "3", "4"]
  • If limit is negative, split returns all of the parsed fields and a trailing null string element if there is a trailing delimiter in the original string.

Example:

"2_3_4".split('_',-2)
=> ["2", "3", "4"]

"2_3_4".split('_',-5)
=> ["2", "3", "4"]

"2_3_4_".split('_',-2)
=> ["2", "3", "4", ""]

"2_3_4_".split('_',-5)
=> ["2", "3", "4", ""]

It would seem that something a little more useful or interesting could have been done with the negative limit.

like image 111
lurker Avatar answered Sep 02 '25 17:09

lurker