A quick tutorial about how to split a Ruby Array.

· Ruby  · 2 min read

Ruby Split Array

A quick tutorial about how to split a Ruby Array.

Split method for a Ruby array

Let’s start with a simple example :

[1, 42, 99, 200].split(42)
# => returns [[1], [99, 200]]

Yikes! It returns a 2D-Array. After all, it’s logical because you have asked to separate the initial Array into multiple parts. But when this line appears within thousands lines of code, it’s easy to forget about it.

Side note : the same operation is not possible in native JavaScript so far.

More examples

Given the answer above, here is how you apply the .split method for array in various situations :

[1, 42, 99, 200].split()
# => returns [[1], [42], [99], [200]]

Any arguments that doesn’t match any element in the initial array will return the same result :

[1, 42, 99, 200].split("")
# => returns [[1, 42, 99, 200]]

[1, 42, 99, 200].split(101)
# => returns [[1, 42, 99, 200]]

[1, 42, 99, 200].split("foo")
# => returns [[1, 42, 99, 200]]

We can also pass a block :

# This will return the same result as [1, 42, 99, 200].split(42)
[1, 42, 99, 200].split{|x| x % 42 === 0}
# => returns [[1], [99, 200]]

[1, 42, 99, 200].split{|x| x % 2 === 0}
# => returns [[1], [99], []]

Ruby Array .split vs Ruby String .split

String

For a String, the signature is as follow:

  • .split(pattern, limit)
  • limit is a number, to define how much parts can be splitted.
  • pattern is a String or a RegEx

Here is a example with a limit :

# Ruby
myString = "hello_world_dude"
myString.split("_", 2)
// => returns ["hello", "world_dude"]

Array

  • .split(pattern)
  • pattern is a value or a Block
# Ruby
myArray = [1, "e", 22]
myArray.split("e")
// => returns [[1], [22]]
myArray.split{|x| x === "e"}
// => returns [[1], [22]]

Split a 2D Array

Given the paragraph above, the following example should not surprise you:

# Ruby
arr = [[1,2,3], ["a","b"], [1,12,4]]
arr.split(2)
# => [[[1, 2, 3], ["a", "b"], [1, 12, 4]]]
arr.split(["a", "b"])
# => [[[1, 2, 3]], [[1, 12, 4]]]

Split an Array into chunks

Loot at the each_slice method of the Enumerable module:

[1, 2, 3, 4, 5, 6, 7].each_slice(3)
# => #<Enumerator: ...>
[1, 2, 3, 4, 5, 6, 7].each_slice(3).to_a
# => [[1, 2, 3], [4, 5, 6], [7]]

Enumerators are a feature of Ruby.

Conclusion

Split for an Array is not much different than the usual “split” for a String. Just remind that the result is always an Array that is one dimension bigger than the initial Array.

Share:
Back to Blog

Related Posts

View All Posts »
Rails and Sidekiq tutorial

Rails and Sidekiq tutorial

The need for the existence of background jobs arises very quickly when you create a new Rails application for business purposes. Sidekiq was, for a long time, the de-facto tool of the Rails stack.

Rails and Cypress testing

Rails and Cypress testing

Cypress is very interesting, since it matches one of the core Rails philosophy, which is "value integrated system"