0
0
RubyHow-ToBeginner · 3 min read

How to Split String in Ruby: Syntax and Examples

In Ruby, you can split a string into an array of substrings using the split method. You provide a separator as an argument to split, and it divides the string wherever the separator appears.
📐

Syntax

The basic syntax to split a string in Ruby is:

string.split(separator, limit)
  • string: The original string you want to split.
  • separator: The character(s) or pattern where the string will be divided. If omitted, it splits on whitespace.
  • limit (optional): Limits the number of splits; the last element contains the rest of the string.
ruby
string.split(separator = nil, limit = nil)
💻

Example

This example shows how to split a sentence into words using a space as the separator.

ruby
sentence = "Hello world from Ruby"
words = sentence.split(" ")
puts words.inspect
Output
["Hello", "world", "from", "Ruby"]
⚠️

Common Pitfalls

One common mistake is forgetting that split returns an array, not a string. Also, if you don't provide a separator, it splits on whitespace by default, which might not be what you want. Another pitfall is using a wrong separator that doesn't exist in the string, which returns the whole string as one element.

ruby
text = "apple,banana,orange"
# Wrong: splitting without separator when commas are present
wrong_split = text.split("")
# Right: splitting by comma
right_split = text.split(",")
puts wrong_split.inspect
puts right_split.inspect
Output
["apple,banana,orange"] ["apple", "banana", "orange"]
📊

Quick Reference

  • split without arguments splits on whitespace.
  • Use a string or regex as separator.
  • Limit argument controls number of splits.
  • Returns an array of substrings.

Key Takeaways

Use split to divide a string into an array by a separator.
If no separator is given, split divides on whitespace.
Always remember split returns an array, not a string.
Use the optional limit to control how many splits happen.
Choose the correct separator to get the expected split results.