Rails Insights

Essential String Methods in Ruby

Introduction

Strings are a fundamental data type in Ruby, and there are many built-in methods that allow you to manipulate and work with strings in various ways. In this article, we will explore some of the essential string methods in Ruby that you should be familiar with.

1. length

The length method returns the number of characters in a string:

str = "Hello, World!"
puts str.length
# Output: 13

2. upcase and downcase

The upcase method converts all characters in a string to uppercase, while the downcase method converts all characters to lowercase:

str = "Hello, World!"
puts str.upcase
# Output: HELLO, WORLD!

puts str.downcase
# Output: hello, world!

3. strip

The strip method removes leading and trailing whitespace from a string:

str = "   Hello, World!   "
puts str.strip
# Output: Hello, World!

4. split

The split method splits a string into an array of substrings based on a delimiter:

str = "Hello, World!"
arr = str.split(" ")
puts arr
# Output: ["Hello,", "World!"]

5. include?

The include? method checks if a string contains a specific substring:

str = "Hello, World!"
puts str.include?("World")
# Output: true

6. sub and gsub

The sub method replaces the first occurrence of a substring with another substring, while the gsub method replaces all occurrences:

str = "Hello, World!"
new_str = str.sub("Hello", "Hi")
puts new_str
# Output: Hi, World!

new_str = str.gsub("l", "z")
puts new_str
# Output: Hezzo, Worzd!

7. reverse

The reverse method reverses a string:

str = "Hello, World!"
puts str.reverse
# Output: !dlroW ,olleH

Conclusion

These are just a few of the essential string methods in Ruby that you can use to manipulate and work with strings. By familiarizing yourself with these methods, you will be better equipped to handle string manipulation tasks in your Ruby programs.

Published: June 28, 2024

© 2024 RailsInsights. All rights reserved.