Work with String Methods in Ruby

Introduction

Ruby strings have several inbuilt ways that create it straightforward to switch and manipulate text, a standard task in several programs.

You’ll use string ways to see the length of a string, index and split strings to extract substrings, add and take away whitespace and alternative characters, amendment the case of characters in strings, and realize and replace text.

When you are done, you will be ready to incorporate these ways into your own programs.

Determining String Length

String methodology length returns the number of characters during a string. This methodology is helpful for once you ought to enforce the minimum or most word lengths, or to truncate larger strings to be at intervals sure limits to be used as abbreviations.

The example that prints the length of a sentence:

open_source = "Sammy contributes to open source."
print open_source.length

Output:

33

Keep in mind that each character, together with letters, numbers, whitespace characters, and symbols, are counted since it’s a part of the string.

To check to examine if a string is empty, you’ll check to examine if its length is zero, otherwise, you will use the empty? method:

name = ""
name.empty? # true

name = "Sammy"
name.empty? # false

name = " "
name.empty? # false

Let’s check up on the way to we tend to index strings and access a string’s contents.

Accessing Characters at intervals a String

To print or work with a number of the characters during a string, use the slice methodology to urge the half you would like.

Like arrays, wherever every component corresponds to an index, every of a string’s characters additionally corresponds to an index, beginning with the index zero.

For the string Sammy the index breakdown sounds like this:

o 1 2 3 4
S a m m y

Slice methodology allows you to grab one character or a variety of characters. Passing one whole number returns the character at that index. Passing 2 integers, separated by a comma, tells slice to come back all the characters from the primary index to the last index, inclusive. The slice methodology additionally accepts a variety, such as 1..4, to specify the characters to extract:

"Sammy".slice(0)     # "s"
"Sammy".slice(1,2) # "am"
"Sammy".slice(1..4) # "ammy"

The [ ] syntax is AN alias for the slice, therefore you’ll treat strings like arrays:

"Sammy"[0]     # "s"
"Sammy"[1,2] # "am"
"Sammy"[1..4] # "ammy"

You may also access one character from the tip of the string with a negative index. -1 would allow you to access the last character of the string, -2 would access the second-to-last, and so on.

Finally, you’ll convert the string to an array of characters with the chars method:

"sammy".chars    # ["S", "a", "m", "m", "y"]

This will be helpful for manipulating or remodeling the characters within the string.

Next, let’s check up on the way to alter the case of the characters during a string.

Converting to higher and lower-case letter

The upcase and downcase ways come back a string with all the letters of a creative string regenerate to upper- or lower-case letters. Any characters within the string that aren’t letters won’t be modified.

Let’s convert the string Sammy Shark to be all higher case:

name = "Sammy Shark"
print name.upcase

Output:

SAMMY SHARK

Now, let’s convert the string to be all lower case:

print name.downcase

Output:

SAMMY SHARK

Upcase and downcase functions create it easier to judge and compare strings by creating case consistent throughout. for instance, if you fire a username and therefore the user enters the username with a capital, you’ll minuscule the user’s input and compare it against a minuscule best-known price.

Ruby strings even have a capitalize methodology that returns a replacement string with the primary character capitalized:

"sammy".capitalize    # "Sammy"

This may be a convenient methodology, however, use caution however you employ it; it solely capitalizes the primary letter, therefore, it’d not perpetually match the employment case you would like.

It additionally provides a swapcase methodology that returns a string with the casing swapped:

text = "Sammy"
print text.swapcase

Output

sAMMY

The downcase, upcase, capitalize and swapcase ways all come back a replacement string and leave the present string unedited. this is often necessary to recollect if you are doing one thing aside from straight off printing out the text. Take a glance at the subsequent example:

text = "sammy"
text.capitalize

print "Hello, #{text}!"

Output:

Hello, sammy!

Even tho’ we tend to know as exploit the text variable, we tend to ne’er captured the worth came by capitalizing. We’d rewrite the program like this:

text = "sammy"
text = text.capitalize

print "Hello, #{text}!"

Output:

Hello, Sammy!

You will use downcase!, upcase!, capitalize! and swapcase! to switch the first string instead:

text = "sammy"
text = text.capitalize!

print "Hello, #{text}!"

Be careful tho’. There area unit disadvantages to mutating the first string. Ruby provides each way, therefore, you’ll opt for the one that matches your wants.

Now let’s add and take away whitespace from strings.

Padding and baring Strings

If you are writing a program that has got to format some text, you may typically realize that you will need to feature some area before of, after, or around a string so as to form it line up with alternative information.

And alternative times, you will need to get rid of gratuitous characters from the start or finish of your strings, like additional whitespace or special characters.

To surround a string with areas, use the middle method:

"Sammy",center(21)    # "        Sammy        "

You will specify a string because of the second argument if you wish to use a distinct character:

" [Sammy] ".center(21, "<>")   # "<><><> [Sammy] <><><>"

The ljust and rjust ways add areas or characters to the left or right facet of a string and work specifically just like the center method:

"Sammy".ljust(20)         # "Sammy               "
"Sammy".rjust(20) # " Sammy"
"Sammy".rjust(20, "!") # "!!!!!!!!!!!!!!!Sammy"

To take away leading areas from a string, use the rstrip methodology. To get rid of trailing areas, use lstrip. Use strip to get rid of each leading and trailing spaces:

"        Sammy".rstrip    # "Sammy"
"Sammy ".lstrip # "Sammy"
" Sammy ".strip # "Sammy"

You will use the center!, ljust!, rjust!, lstrip!, rstrip!, and strip! ways to switch the first string.

Sometimes you’ll have to get rid of characters from the tip of a string. Ruby’s chop methodology will simply that; it removes the last character from a string:

"Sammy".chop     # "Samm"

This is particularly helpful for removing the newline character (\n) from strings:

"This string has a newline\n".chop

The chop methodology leaves the first string intact, returning a replacement string. The chop! methodology modifies the present string in situ.

The chomp methodology will take away multiple characters from the tip of a string:

"Sammy".chomp("my")    # "Sam"

If you do not specify a string to get rid of, chomp can take away the newline:

"This string has a newline\n".chomp   # "This string has a newline

However, if the string does not contain a newline character, chomp simply returns the first string:

"Sammy".chomp     # "Sammy"

This makes chomp a touch safer to use once removing newlines than the chop methodology, that perpetually removes the last character.

Ruby contains a chomp! a methodology that mutates the first string and returns the modified string if it performed a replacement. However, not like chomp, the chomp! methodology returns null if it did not alter the string:

string = "Hello\n"
string.chomp! # "Hello"

string = "Hello"
string.chomp! # nil

Next, let’s check up on the way to seek for text in strings.

Finding Characters and Text

Sometimes you would like to see whether or not or not a string contains another string.

The include? methodology checks to examine if a string contains another string. It returns true if the string exists and false if not:

"Sammy".include?("a")   # true
"Sammy".include?("b") # false

The index methodology returns the index of a personality. It may also establish the index of the primary character of a substring. And it returns null if the character or substring does not exist:

"Sammy".index("a")     # 1
"Sammy".index("mm") # 2
"Sammy".index("Fish") # nil

The index methodology solely finds the primary occurrence tho’. Here’s AN example with an extended string:

text = "Sammy contains a balloon"
text.index("a") # 1

The string Sammy contains a balloon has four occurrences of the letter “a”. However, index solely found the primary occurrance. you will have to jot down one thing a lot of specific to find one amongst the opposite occurrances.

For example, you may convert the string to AN array of characters and use array ways to tell through the results and choose the indices for the character. Here’s one methodology for doing that:

[1, 7, 10, 13]

each_with_index returns a two-dimensional array containing the an entry for every character and its index. choose whittles it all the way down to simply the entries wherever the character may be a, and map converts the 2-dimensional array into a one-dimensional array of the indices.

In addition to trying to find characters during a string, you’ll check to examine if a string starts with a personality or substring victimization the start_with? method:

text = "Sammy contains a balloon"
text.start_with?("s") # true
text.start_with?("Sammy has" # true

The start_with? methodology accepts multiple strings and returns true if any of them match:

text = "Sammy contains a balloon"
text.start_with?("Sammy the Shark", "Sammy") # true

In this instance, “Sammy the Shark” is not found, however, “Sammy” is, therefore the comeback price is true.

You will use the end_with? methodology to examine if a string ends with the given substring. It works specifically like start_with?:

text = "Sammy contains a balloon"
text.end_with?("balloon") # true
text.end_with?("boomerang") # false
text.end_with?("boomerang", "balloon") # tru

We’ve checked out ways that to search out text, therefore let’s check up on the way to replace that text with completely different text.

Replacing Text in Strings

The realize and replace feature in word processors allows you to seek for a string and replace it with another string. you’ll try this in Ruby with the sub and gsub ways.

The sub methodology replaces a part of a string with another.

Sammy now not has the balloon; it flew away. Let’s amendment the substring “has” to “had”.

balloon = "Sammy contains a balloon"
print balloon.sub("has","had")

Output

Sammy had a balloon.

The sub methodology solely replaces the primary occurrence of the match with the new text. Let’s use a changed string that has 2 occurrences of the word has:

balloon = "Sammy has a balloon. The balloon has a ribbon"
print balloon.sub("has","had")

Output

Sammy had a balloon. The balloon has a ribbon

Only the primary occurrence modified.

To amendment all of them, use the gsub methodology, that performs international substitution:

balloon = "Sammy has a balloon. The balloon has a ribbon"
print balloon.gsub("has","had")

Output:

Sammy had a balloon. The balloon had a ribbon

The sub and gsub ways perpetually come back new strings, departure the originals unqualified. Let’s demonstrate this by ever-changing “balloon” to “boomerang” in our string:

text = "Sammy has a balloon"
text.gsub("ballooon", "boomerang")
print text

Output:

Sammy has a balloon

The output does not show the result we’re trying to find, as a result of whereas we tend to did specify the substitution, we tend to never assign gsub to a replacement variable. to urge the result we’d like, we tend to may rewrite the program like this:

text = "Sammy has a balloon"
text = text.sub("ballooon", "boomerang")
print text

Alternatively, you’ll use sub! instead, that modifies the first string. Let’s do this by doing a handful of string replacements. We’ll amendment “red balloon” to “blue boomerang”:

text = "Sammy has a red balloon"
text.sub!("red", "blue")
text.sub!("balloon", "boomerang")
print text

Output:

Sammy has a blue boomerang

You will use the gsub! methodology to try to to a worldwide substitution in situ further.

The sub and gsub ways settle for regular expressions for the search pattern. Let’s replace all the vowels within the string with the @ symbol:

"Sammy has a red balloon".gsub /[aeiou]/, "@"
"S@mmy h@s @ r@d b@ll@@n"

The replacement price does not need to be a string. You’ll use a hash to specify however individual characters or items ought to get replaced. Let’s replace all occurrences of the letter a with @ and every one the o characters with zeros:

"Sammy has a red balloon".gsub /[aeiou]/, {"a" => "@", "o" => "0"}
# "S@mmy h@s @ rd b@ll00n"

You will use this to perform a lot of advanced substitutions with less code.

Conclusion

You worked with and manipulated strings victimization a number of the inbuilt ways for the string information kind. you furthermore might learn that a lot of the ways for operating with strings are available 2 variants: one that leaves the string unchanged, and one that modifies the first string. that one you employ depends on your wants. Ruby provides you the flexibleness to decide on however you wish to figure together with your information. However, writing code that does not modify existing information will be easier to right later.

Categorized in: