Split Strings with Trailing Nulls
Ruby's String
.split
accepts an optional number argument, and this lets us do some interesting things.
For instance, here is a naive full name splitter using such an argument:
> first_name, last_name = 'Benico del Toro'.split(' ', 2)
=> ["Benicio", "del Toro"]
It's naive because it doesn't work on names like 'Philip Seymour Hoffman'
, returning ["Philip", "Seymour Hoffman"]
.
Today I learned this argument can be negative. When it is, there is no limit to the number of fields returned, and trailing null fields are not suppressed:
> "Academy Award Winner....".split(".", 2)
=> ["Academy Award Winner", "..."]
> "Academy Award Winner....".split(".", -2)
=> ["Academy Award Winner", "", "", "", ""]
The actual value of the negative number seems to be irrelevant:
> "Academy Award Winner....".split(".", -1)
=> ["Academy Award Winner", "", "", "", ""]
> "Academy Award Winner....".split(".", -12)
=> ["Academy Award Winner", "", "", "", ""]
http://ruby-doc.org/core-2.3.0/String.html#method-i-split
Tweet