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:
Syntax
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
csv_line = "apple,banana,cherry"
parts = csv_line.split(",")
puts parts.inspect
joined = parts.join(" | ")
puts joined
Login to try C/C++/Java/PHP code in the editor
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
- Splitting on a separator and expecting empty trailing items, when
"a,b,,".split(",")drops them. - Calling
joinon a string instead of an array, sincejoinbelongs to arrays. - Forgetting that
splitwith 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: