0
0
Rubyprogramming~5 mins

Split and join methods in Ruby

Choose your learning style9 modes available
Introduction

Split breaks a string into parts. Join puts parts back together into one string.

When you want to separate words in a sentence into a list.
When you need to combine a list of words into a sentence.
When processing data from a file where items are separated by commas.
When formatting output by joining pieces with a special character.
Syntax
Ruby
string.split(separator = nil, limit = nil)
array.join(separator = '')

split breaks a string into an array using the separator.

join combines array elements into a string with the separator between them.

Examples
Splits the string at each comma into an array of fruits.
Ruby
"apple,banana,orange".split(",")
Splits the string at spaces by default.
Ruby
"hello world".split
Joins array elements with a dash between them.
Ruby
["a", "b", "c"].join("-")
Joins array elements without any separator.
Ruby
["one", "two", "three"].join
Sample Program

This program splits a sentence into words, prints each word, then joins them with dashes and prints the result.

Ruby
sentence = "Ruby is fun"
words = sentence.split
puts "Words:"
words.each { |word| puts word }

joined = words.join("-")
puts "Joined with dashes:"
puts joined
OutputSuccess
Important Notes

If you don't give a separator to split, it splits on whitespace.

join works only on arrays, not strings.

Both methods help change how text is organized and displayed.

Summary

split turns a string into an array by cutting at separators.

join turns an array into a string by connecting elements with a separator.

Use them to easily change between strings and lists of words or parts.