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.
The length
method returns the number of characters in a string:
str = "Hello, World!" puts str.length # Output: 13
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!
The strip
method removes leading and trailing whitespace from a string:
str = " Hello, World! " puts str.strip # Output: Hello, World!
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!"]
The include?
method checks if a string contains a specific substring:
str = "Hello, World!" puts str.include?("World") # Output: true
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!
The reverse
method reverses a string:
str = "Hello, World!" puts str.reverse # Output: !dlroW ,olleH
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.
© 2024 RailsInsights. All rights reserved.