0
0
RubyHow-ToBeginner · 3 min read

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]: Extracts length characters starting at index start.
  • string[range]: Extracts characters within the given range of indices.
  • string[start..end]: Inclusive range from start to end.
  • string[start...end]: Exclusive range, excludes the end index.

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 nil instead 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

SyntaxDescriptionExample
string[start, length]Slice from index start for length charactersstr[2, 4] => "gram"
string[range]Slice characters in the given rangestr[2..5] => "gram"
string[start..end]Inclusive range slicestr[0..3] => "Prog"
string[start...end]Exclusive range slicestr[0...3] => "Pro"
string[-n, length]Slice from n-th last characterstr[-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.