Working with strings is one of the most common things you’ll do when working with Ruby or Ruby on Rails. Luckily, Ruby has all sorts of great built-in methods that help us work with strings.
I put together this guide so you know what methods are available to you when working with strings in Ruby.
I’d like to shoutout to this article which inspired me to write this guide.
How to get a string’s length in Ruby.
This is one of the most common things you’ll do when working with strings. You can use the size or length methods to get the number of characters of a string in Ruby.
There are two ways to determine if a string is empty in Ruby. You can compare the size or length to 0 or you can use the empty method.
"".size == 0 "".empty?
You can extract a substring from a string in Ruby by using a starting index number and the number of characters you want to get.
"string"[0,2] # "st"
With this method, you can see if a string contains substring.
"This is a string".include?("string")
HINT: There are many methods in Ruby that end with a question mark (?) that return a boolean.
Ruby has downcase and upcase methods you can use to easily change the case of a string.
"hi".upcase # "HI" "Hi".downcase # "hi"
You can compare strings using “==”, but strings are case sensitive. Because of this, it’s common practice to call downcase or upcase on both strings to convert them into the same case before comparing them.
"String".downcase == "sTring".downcase "another String".upcase == "ANOTHER string".upcase
Sometimes you want to get rid of whitespace at the beginning or end of a string. Use the strip method to take care of it.
" string ".strip # "string
You can use the split method to convert a string into an array in Ruby You can choose to pass it an argument if you want to, but you don’t have to.
"string".split # ["string"] "string".split("") # ["s", "t", "r", "i", "n", "g"] "this is a string".split(" ") # ["this", "is", "a", "string"]
Just use the shovel operator (<<) to concat strings in Ruby.
"Hello" << " World" # "Hello World"
The to_i method is the method you’re looking for here.
"42".to_i # 42
If you call this method on a string, you get 0.
"efe234".to_i # 0
You can convert the integer to a string and then back into an integer and compare it to the original. This has limited uses and won’t catch all edge cases.
"32".to_i.to_s == "32" # true
A more robust way is to use regex to check if the input is a number.
"54321".match?(/\A-?\d+\Z/) # true
Use %Q to create a multi-line string in ruby.
string = %Q( this is a string )
The starts_with? method is the method to use here.
"Ruby".starts_with?("R") # true "Ruby is great".starts_with?("Ruby") # true
And we can use the ends_with? method for this one.
"Ruby".starts_with?("y") # true "Ruby is great".starts_with?("great") # true
This guide will most likely evolve once I can think of some useful string methods in Ruby.
If you want to learn more about web development, make sure to follow me on Twitter.