1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-04 23:58:01 +00:00
Files
til/ruby/limit-split.md
2015-02-13 19:26:50 -06:00

1.0 KiB

Limit Split

I've only ever used Ruby's String#split with the delimiter argument (e.g. "this string has spaces".split(" ")). This method has another argument that can be specified, the limit argument. With limit, you can limit the number of times that the split happens.

"this string has many spaces".split(" ")
# => ["this", "string", "has", "many", "spaces"]
"this string has many spaces".split(" ", 3)
# => ["this", "string", "has many spaces"]

There are surely many use cases, but one that stands out (from The Rails 4 Way) is for splitting a name into first and last names.

"Josh Branchaud".split(" ", 2)
# => ["Josh", "Branchaud"]
"David Heinemeier Hansson".split(" ", 2)
# => ["David", "Heinemeier Hansson"]

This really simplifies the code that is needed to make the following example work:

def create_user(name)
  user = User.new
  user.first_name, user.last_name = name.split(" ", 2)
  user.save
end