15 Most Useful Methods Of String In Ruby

15 Most Useful Methods Of String In Ruby


In Ruby, strings are not just simple data types but are objects with their methods. This enables developers to perform complex manipulations and inquiries efficiently.


In this article, I will explore some of the most essential and powerful Ruby string methods, complete with practical examples to help you master string handling in your projects.

Initialization

a = String.new # []

b = ''

c = ""        

Basic String Operations

  1. length or size: Returns the number of characters in the string.

"Hello".length  # Output: 5        

2. strip: Removes leading and trailing whitespace from the string.

" hello ".strip  # Output: "hello"

" he llo ".strip  # Output: "he llo"        

3. downcase and upcase: Converts all of the characters in the string to lowercase or uppercase, respectively.

"Hello".downcase  # Output: "hello" 

"hello".upcase    # Output: "HELLO"        

4. capitalize: Capitalize the first character of the string.

"hello".capitalize  # Output: "Hello"        

String Matching and Substitution

5. include?: Checks if the string contains a given substring.

"hello".include?("lo")  # Output: true        

6. gsub: Returns a copy of the string with all occurrences of a pattern substituted for the second argument.

"hello".gsub('l', 'r')  # Output: "herro"        

7. match: Matches the string against a regular expression.

"hello".match(/[aeiou]/)  # Output: #<MatchData "e">

"hello".match(/[au]/) # Output: nil        

String Splitting and Joining

8. split: Divides the string into substrings based on a delimiter (pattern or string), returning an array of these substrings.

"hello world".split  # Output: ["hello", "world"] 

"hello-world".split('-')  # Output: ["hello", "world"]        

9. join (used on arrays): Concatenates the elements of an array to form a single string, separated by the string it's called on.

["hello", "world"].join(" ")  # Output: "hello world"

["hello", "world"].join(", ") # "hello, world"        

Advanced Manipulation

10. reverse: Reverses the characters in the string.

"hello".reverse  # Output: "olleh"        

11. slice: Extracts a substring from the string using a range or index.

"hello".slice(0, 2)  # Output: "he"        

12. chomp: Removes the trailing newline character from the string if it exists.

"hello\n".chomp  # Output: "hello"        

13. chop: Removes the last character of the string.

"hello".chop  # Output: "hell"        

String Encoding and Case Conversion

14. swapcase: Returns a new string with all uppercase letters converted to lowercase and vice versa.

"Hello".swapcase  # Output: "hELLO"        

15. tr: Translates characters of the string to other characters.

"hello".tr('el', 'ip')  # Output: "hippo"        

Time for a bonus method ??

16. squeeze: Squeezes sequences of the same character in the string into a single character.

"yellow moon".squeeze  # Output: "yelow mon"        

Conclusion

Ruby provides a rich set of string methods that allow developers to handle text in a variety of powerful ways. Whether you are preparing data for display, performing complex searches, or simply manipulating strings to meet the requirements of an algorithm, understanding these methods can greatly enhance your productivity and the reliability of your code.


Follow Anuraag Misshra to advance your knowledge of Ruby on Rails and interview preparation.


#RubyOnRails #Ruby #Programming #SoftwareDevelopment #Coding #interview

Dheeraj Haran

Accomplished L&D Leader with 12+ years of experience in high-impact training, optimizing processes, and driving capability building.

10 个月

Looking forward to diving into it! ?? Anuraag Misshra

要查看或添加评论,请登录

Anuraag Misshra的更多文章

  • 15 Most Useful Methods Of Array In Ruby

    15 Most Useful Methods Of Array In Ruby

    As a Ruby on Rails developer, mastering the array methods provided by Ruby not only enhances your code efficiency but…

    2 条评论

社区洞察

其他会员也浏览了