Ruby Split Array

Posted December 22, 2022 - tagged ruby

3 min read

Split is a very common method not only in Ruby, but also in the programming world. Let's see what does .split means for 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.

2023 update

👉 Bootrails is now affiliated with a well-known starter kit.
Take care ! Health first. 🙏
David.