From 2d12004407b2763991af95395e7a2307d3f828c3 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 13 Feb 2015 19:26:50 -0600 Subject: [PATCH] Add the Limit Split til to the ruby directory. --- ruby/limit-split.md | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 ruby/limit-split.md diff --git a/ruby/limit-split.md b/ruby/limit-split.md new file mode 100644 index 0000000..a04a5cf --- /dev/null +++ b/ruby/limit-split.md @@ -0,0 +1,37 @@ +# Limit Split + +I've only ever used Ruby's +[`String#split`](http://ruby-doc.org//core-2.2.0/String.html#method-i-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. + +```ruby +"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](https://leanpub.com/tr4w)) is for splitting a name into *first* and +*last* names. + +```ruby +"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: + +```ruby +def create_user(name) + user = User.new + user.first_name, user.last_name = name.split(" ", 2) + user.save +end +```