The second number is how many characters you want.
You can also use a range if you want to do something like “get all the characters but the last one”.
Example:
string = "abc123"
string[0..-2]
# "abc12"
Now, the first index is still the starting index, but the second index is the ending index (inclusive). This -2 is the second to last character, and -1 is the end of the string.
If you want to remove or replace the substring.
You can do this:
string[0..2] = ""
p string
# "123"
Very nice!
How to Find Out If a String Contains Another String
What’s the easiest way to find if a string is included in another string?
The include? method:
string = "Today is Saturday"
string.include?("Saturday")
# true
You can also use the index method:
string = "Today is Sunday"
string.index("day")
# 2
This method looks for partial words & instead of returning true or false it will give you the index where the start of this string is found.
In this example, index is finding the “day” in “Today”.
If you want to find patterns (like all the words containing the word “day”) you are looking for regular expressions.
How to Pad a Ruby String
One way to pad a string is to use the rjust method with two arguments:
But if you are working with CSV data specifically you may want to consider using the CSV class from the standard library. This class can do things like reading column headers, so it makes things easier for you.
Convert an Array to a String
If you would like to take an array of strings & join these strings into a big string you can use the join method.
Example:
arr = ['a', 'b', 'c']
arr.join
# "abc"
It’s also possible to pass an argument to join, this argument is the character separator.
Example:
arr = ['a', 'b', 'c']
arr.join("-")
# "a-b-c"
Convert a String Into An Integer
If you want to convert a string like "49" into the Integer 49 you can use the to_i method.
Example:
"49".to_i
Notice that if you try this with a string that contains no numbers then you will get 0.
Example:
"a".to_i
# 0
Check If A String Is A Number
Would you like to know if a string is made of only whole numbers?
Note: The match? method was introduced in Ruby 2.4, you can use match (without the question mark) on older versions.
This code uses a regular expression, let me translate it for you:
“From the start of the string (\A) check if there is an optional dash (-?, for negative numbers), then make sure there are some numbers in there (\d+) & nothing else until the end of the string (\Z).”
How to Append Characters
You can build up a big string from smaller strings by appending characters to an existing string. We also call this string concatenation.
How to Convert a String to Upper or Lowercase in Ruby
If you would like to convert a string to all upper case you can use the upcase method.
Example:
"abcd".upcase
# "ABCD"
And if you want to convert to lower case you can use the downcase method.
Example:
"ABCD".downcase
# "abcd"
How to Create Multiline Strings
You can create multi-line strings in two different ways.
One is by using heredocs:
b = <<-STRING
aaa
bbb
ccc
STRING
And another is by using %Q:
a = %Q(aaa
bbb
ccc
)
How to Replace Text Inside a String Using The Gsub Method
If you want to replace text inside a string use the gsub method.
Let's replace the word "dogs" with "cats":
string = "We have many dogs"
string.gsub("dogs", "cats")
# "We have many cats"
If you want to remove the string use an empty string as the 2nd argument.
Example:
string = "abccc"
string.gsub("c", "")
# "ab"
Now:
The gsub method returns a new string.
If you want to apply the changes to the original string you can use the gsub! method.
The gsub method also takes regular expressions as an argument so you can replace patterns instead of exact words.
Here's an example:
string = "We have 3 cats"
string.gsub(/\d+/, "5")
# "We have 5 cats"
This replaces all the numbers (\d+) in the string with the number 5.
One more way to use this method, with a block:
title = "the lord of the rings"
title.gsub(/\w+/) { |word| word.capitalize }
# "The Lord Of The Rings"
What about gsub vs sub?
Well, sub is the same as gsub, but it will only replace the first match.
Gsub replaces ALL matches.
How to Remove the Last Character From a String
If you are asking the user for some input (using the Kernel#gets method) then you will have a newline character (\n) at the end of your string, this prevents you from comparing the string directly.
Example:
puts "What's your name?"
name = gets
# type something...
The best way to remove that extra newline character (\n) is to use the chomp method.
Example:
name = gets.chomp
Since Ruby 2.3 the chomp method takes an optional argument that allows you to remove the characters you want to remove.
Example:
"abcd?".chomp("?")
# "abcd"
And if the character is not there it will return the original string.
How to Change String Encodings
Strings are stored as a sequence of bytes, they are turned into the characters that you can see based on their encoding.
For example, the number 65 in the ASCII encoding represents the letter "A".
But there are also more complex encodings, like UTF-8, which allow you to represent characters from different languages (Chinese, etc.) & even emojis.
To find out the current encoding for a string you can use the encoding method.
"abc".encoding
# Encoding:UTF-8
When reading a file from disk or downloading some data from a website you may run into encoding problems.
You can often fix that problem by enforcing the encoding.
Like this:
"abc".force_encoding("UTF-8")
Counting Characters
You can count how many times a character appears in a string by using the count method.
You learned about many string methods, like join & split to break down strings into arrays, gsub to replace text inside strings & strip to trim out extra white space.
Since you may want to reference this page later make sure to bookmark it & share it with all your Ruby friends 🙂
Thanks for reading!
Related
17 comments
Maddox says
5 years ago
Nice post. Very helpful roundup and explanation of string methods.
In your post, you mentioned the method ‘casecmp?’ as a way to do case-insensitive string comparisons. However, you also recommended not to use it and instead prefer comparing up/downcased strings.
I found your page because I was trying to figure out how to switch from downcase with the spaceship operator to casecmp, because rubocop blows up demanding casecmp, and we use rubocop for styling. casecmp is much faster when benchmarking, which is why I suspect the style guide is directing us that way. Meanwhile, I’m still not getting casecmp to work properly. I may need to disable rubocop there, but that’s not my first choice.
I ended up getting it to work just fine, and my company uses rubocop to process our pull requests, as did the last place it works. I suspect we’ll start seeing more of it. In any case, I’m glad to see your post! Every piece of info helps out here!
In your “How to Remove the Last Character From a String” topic the very lasg sentence says “And if the character is not there it will return the original array” I believe you meant string not array. Love the article though it didn’t occur to me that String#+ creates a new string object every time and String#<< does proper string concatenation to the original string! Cheers.