How to Slice String in Ruby: Syntax and Examples
In Ruby, you can slice a string using
string[start, length] or string[range] to extract parts of it. The start is the index where slicing begins, and length is how many characters to take. You can also use negative indices to count from the end.Syntax
You can slice a string in Ruby using these patterns:
string[start, length]: Extractslengthcharacters starting at indexstart.string[range]: Extracts characters within the given range of indices.string[start..end]: Inclusive range fromstarttoend.string[start...end]: Exclusive range, excludes theendindex.
Indices start at 0. Negative indices count from the end (-1 is last character).
ruby
str = "Hello, world!" # Using start and length slice1 = str[7, 5] # "world" # Using range slice2 = str[7..11] # "world" # Using exclusive range slice3 = str[7...12] # "world" # Using negative index slice4 = str[-6, 5] # "world"
Example
This example shows how to slice different parts of a string using indices and ranges.
ruby
str = "Programming" puts str[0, 6] # Output: "Progra" puts str[3..6] # Output: "gram" puts str[-4, 4] # Output: "ming" puts str[0...3] # Output: "Pro" puts str[100, 2] # Output: nil (index out of range)
Output
Progra
gram
ming
Pro
Common Pitfalls
Common mistakes when slicing strings in Ruby include:
- Using an index or range outside the string length returns
nilinstead of an error. - Confusing inclusive (
..) and exclusive (...) ranges. - Forgetting that indices start at 0, so the first character is at index 0.
Always check if the result is nil before using it.
ruby
str = "Example" # Wrong: expecting error but returns nil puts str[10, 3] # nil # Right: check for nil slice = str[10, 3] if slice.nil? puts "Slice out of range" else puts slice end
Output
nil
Slice out of range
Quick Reference
| Syntax | Description | Example |
|---|---|---|
| string[start, length] | Slice from index start for length characters | str[2, 4] => "gram" |
| string[range] | Slice characters in the given range | str[2..5] => "gram" |
| string[start..end] | Inclusive range slice | str[0..3] => "Prog" |
| string[start...end] | Exclusive range slice | str[0...3] => "Pro" |
| string[-n, length] | Slice from n-th last character | str[-4, 3] => "ram" |
Key Takeaways
Use string[start, length] or string[range] to slice strings in Ruby.
Indices start at 0; negative indices count from the end.
Inclusive ranges (..) include the end index; exclusive ranges (...) do not.
Out-of-range slices return nil, not errors.
Always check for nil when slicing with uncertain indices.