String Functions in Ruby

Ruby provides many useful string-related methods. Here are some examples to give you a sense of the language’s string manipulation capabilities.

# We define a shorthand for puts to make our examples more concise
def p(*args)
  puts(*args)
end

# Here's a sample of the methods available for strings in Ruby.
# These are methods on the String object itself, so we call them
# directly on the string. You can find more methods in the Ruby
# documentation for the String class.

p "Contains:  #{"test".include?("es")}"
p "Count:     #{"test".count("t")}"
p "Start with: #{"test".start_with?("te")}"
p "End with:   #{"test".end_with?("st")}"
p "Index:     #{"test".index("e")}"
p "Join:      #{["a", "b"].join("-")}"
p "Repeat:    #{"a" * 5}"
p "Replace:   #{"foo".gsub("o", "0")}"
p "Replace:   #{"foo".sub("o", "0")}"
p "Split:     #{"a-b-c-d-e".split("-")}"
p "Downcase:  #{"TEST".downcase}"
p "Upcase:    #{"test".upcase}"

When you run this Ruby script, you’ll get the following output:

$ ruby string_functions.rb
Contains:  true
Count:     2
Start with: true
End with:   true
Index:     1
Join:      a-b
Repeat:    aaaaa
Replace:   f00
Replace:   f0o
Split:     ["a", "b", "c", "d", "e"]
Downcase:  test
Upcase:    TEST

In Ruby, string manipulation is often more straightforward than in some other languages. Many operations that require separate functions in other languages are methods on the String object in Ruby. This object-oriented approach makes string manipulation in Ruby intuitive and easy to read.

Ruby’s string methods are powerful and flexible. The gsub method, for example, replaces all occurrences of a pattern, while sub replaces only the first occurrence. The * operator can be used to repeat a string, and array methods like join work seamlessly with strings.

Remember to consult the Ruby documentation for a full list of available string methods and their usage.