Today I Learned

hashrocket A Hashrocket project

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", "", "", "", ""]

See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.