← Back to Ruby Course | Chapter 3: Strings | Lesson 6 of 7

split and join

split cuts a piece of text into an array wherever a separator appears, like snipping a ribbon. join does the opposite and ties the pieces back into one text.

In this page:

  1. split and join
Syntax
ruby
parts = string.split(separator)
joined = array.join(separator)

split and join

String#split(separator) breaks a string into an array of substrings wherever the separator occurs, and Array#join(separator) does the reverse, combining array elements back into a single string.

These are commonly paired when parsing and reconstructing delimited text like CSV data. Calling split with no arguments splits on any whitespace.

Note: text.split with no argument splits on any run of whitespace, which is handy for tokenizing plain sentences.

Example: split and join

markup
csv_line = "apple,banana,cherry"

parts = csv_line.split(",")
puts parts.inspect

joined = parts.join(" | ")
puts joined
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Splitting on a separator and expecting empty trailing items, when "a,b,,".split(",") drops them.
  2. Calling join on a string instead of an array, since join belongs to arrays.
  3. Forgetting that split with no argument splits on whitespace and removes extra spaces.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.