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:

[pastacode lang=”ruby” manual=”open_source%20%3D%20%22Sammy%20contributes%20to%20open%20source.%22%0Aprint%20open_source.length” message=”” highlight=”” provider=”manual”/]

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:

[pastacode lang=”ruby” manual=”name%20%3D%20%22%22%0Aname.empty%3F%20%20%20%20%23%20true%0A%0Aname%20%3D%20%22Sammy%22%0Aname.empty%3F%20%20%20%20%23%20false%0A%0Aname%20%3D%20%22%20%20%20%20%20%22%0Aname.empty%3F%20%20%20%20%23%20false” message=”” highlight=”” provider=”manual”/]

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:

[pastacode lang=”ruby” manual=”%22Sammy%22.slice(0)%20%20%20%20%20%23%20%22s%22%0A%22Sammy%22.slice(1%2C2)%20%20%20%23%20%22am%22%0A%22Sammy%22.slice(1..4)%20%20%23%20%22ammy%22″ message=”” highlight=”” provider=”manual”/]

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

[pastacode lang=”ruby” manual=”%22Sammy%22%5B0%5D%20%20%20%20%20%23%20%22s%22%0A%22Sammy%22%5B1%2C2%5D%20%20%20%23%20%22am%22%0A%22Sammy%22%5B1..4%5D%20%20%23%20%22ammy%22″ message=”” highlight=”” provider=”manual”/]

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:

[pastacode lang=”ruby” manual=”%22sammy%22.chars%20%20%20%20%23%20%5B%22S%22%2C%20%22a%22%2C%20%22m%22%2C%20%22m%22%2C%20%22y%22%5D” message=”” highlight=”” provider=”manual”/]

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:

[pastacode lang=”ruby” manual=”name%20%3D%20%22Sammy%20Shark%22%0Aprint%20name.upcase” message=”” highlight=”” provider=”manual”/]

Output:

SAMMY SHARK

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

[pastacode lang=”ruby” manual=”print%20name.downcase” message=”” highlight=”” provider=”manual”/]

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:

[pastacode lang=”ruby” manual=”%22sammy%22.capitalize%20%20%20%20%23%20%22Sammy%22″ message=”” highlight=”” provider=”manual”/]

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:

[pastacode lang=”ruby” manual=”text%20%3D%20%22Sammy%22%0Aprint%20text.swapcase” message=”” highlight=”” provider=”manual”/]

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:

[pastacode lang=”ruby” manual=”text%20%3D%20%22sammy%22%0Atext.capitalize%0A%0Aprint%20%22Hello%2C%20%23%7Btext%7D!%22″ message=”” highlight=”” provider=”manual”/]

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:

[pastacode lang=”ruby” manual=”text%20%3D%20%22sammy%22%0Atext%20%3D%20text.capitalize%0A%0Aprint%20%22Hello%2C%20%23%7Btext%7D!%22″ message=”” highlight=”” provider=”manual”/]

Output:

Hello, Sammy!

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

[pastacode lang=”ruby” manual=”text%20%3D%20%22sammy%22%0Atext%20%3D%20text.capitalize!%0A%0Aprint%20%22Hello%2C%20%23%7Btext%7D!%22″ message=”” highlight=”” provider=”manual”/]

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:

[pastacode lang=”ruby” manual=”%22Sammy%22%2Ccenter(21)%20%20%20%20%23%20%22%20%20%20%20%20%20%20%20Sammy%20%20%20%20%20%20%20%20%22″ message=”” highlight=”” provider=”manual”/]

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

[pastacode lang=”ruby” manual=”%22%20%5BSammy%5D%20%22.center(21%2C%20%22%3C%3E%22)%20%20%20%23%20%22%3C%3E%3C%3E%3C%3E%20%5BSammy%5D%20%3C%3E%3C%3E%3C%3E%22″ message=”” highlight=”” provider=”manual”/]

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:

[pastacode lang=”ruby” manual=”%22Sammy%22.ljust(20)%20%20%20%20%20%20%20%20%20%23%20%22Sammy%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22%0A%22Sammy%22.rjust(20)%20%20%20%20%20%20%20%20%20%23%20%22%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20Sammy%22%0A%22Sammy%22.rjust(20%2C%20%22!%22)%20%20%20%20%23%20%22!!!!!!!!!!!!!!!Sammy%22″ message=”” highlight=”” provider=”manual”/]

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:

[pastacode lang=”ruby” manual=”%22%20%20%20%20%20%20%20%20Sammy%22.rstrip%20%20%20%20%23%20%22Sammy%22%0A%22Sammy%20%20%20%20%20%20%20%20%22.lstrip%20%20%20%20%23%20%22Sammy%22%0A%22%20%20%20%20%20%20Sammy%20%20%22.strip%20%20%20%20%20%23%20%22Sammy%22″ message=”” highlight=”” provider=”manual”/]

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:

[pastacode lang=”ruby” manual=”%22Sammy%22.chop%20%20%20%20%20%23%20%22Samm%22″ message=”” highlight=”” provider=”manual”/]

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

[pastacode lang=”ruby” manual=”%22This%20string%20has%20a%20newline%5Cn%22.chop” message=”” highlight=”” provider=”manual”/]

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:

[pastacode lang=”ruby” manual=”%22Sammy%22.chomp(%22my%22)%20%20%20%20%23%20%22Sam%22″ message=”” highlight=”” provider=”manual”/]

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

[pastacode lang=”ruby” manual=”%22This%20string%20has%20a%20newline%5Cn%22.chomp%20%20%20%23%20%22This%20string%20has%20a%20newline” message=”” highlight=”” provider=”manual”/]

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

[pastacode lang=”ruby” manual=”%22Sammy%22.chomp%20%20%20%20%20%23%20%22Sammy%22″ message=”” highlight=”” provider=”manual”/]

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:

[pastacode lang=”ruby” manual=”string%20%3D%20%22Hello%5Cn%22%0Astring.chomp!%20%20%20%20%20%23%20%22Hello%22%0A%0Astring%20%3D%20%22Hello%22%0Astring.chomp!%20%20%20%20%20%23%20nil” message=”” highlight=”” provider=”manual”/]

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:

[pastacode lang=”ruby” manual=”%22Sammy%22.include%3F(%22a%22)%20%20%20%23%20true%0A%22Sammy%22.include%3F(%22b%22)%20%20%20%23%20false” message=”” highlight=”” provider=”manual”/]

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:

[pastacode lang=”ruby” manual=”%22Sammy%22.index(%22a%22)%20%20%20%20%20%23%201%0A%22Sammy%22.index(%22mm%22)%20%20%20%20%23%202%0A%22Sammy%22.index(%22Fish%22)%20%20%23%20nil” message=”” highlight=”” provider=”manual”/]

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

[pastacode lang=”ruby” manual=”text%20%3D%20%22Sammy%20contains%20a%20balloon%22%0Atext.index(%22a%22)%20%20%20%20%23%201″ message=”” highlight=”” provider=”manual”/]

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:

[pastacode lang=”ruby” manual=”text%20%3D%20%22Sammy%20contains%20a%20balloon%22%0Atext.start_with%3F(%22s%22)%20%20%20%20%20%20%20%20%20%23%20true%0Atext.start_with%3F(%22Sammy%20has%22%20%20%23%20true” message=”” highlight=”” provider=”manual”/]

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

[pastacode lang=”ruby” manual=”text%20%3D%20%22Sammy%20contains%20a%20balloon%22%0Atext.start_with%3F(%22Sammy%20the%20Shark%22%2C%20%22Sammy%22)%20%23%20true” message=”” highlight=”” provider=”manual”/]

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?:

[pastacode lang=”ruby” manual=”text%20%3D%20%22Sammy%20contains%20a%20balloon%22%0Atext.end_with%3F(%22balloon%22)%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20true%0Atext.end_with%3F(%22boomerang%22)%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20false%0Atext.end_with%3F(%22boomerang%22%2C%20%22balloon%22)%20%20%23%20tru” message=”” highlight=”” provider=”manual”/]

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”.

[pastacode lang=”ruby” manual=”balloon%20%3D%20%22Sammy%20contains%20a%20balloon%22%0Aprint%20balloon.sub(%22has%22%2C%22had%22)” message=”” highlight=”” provider=”manual”/]

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:

[pastacode lang=”ruby” manual=”balloon%20%3D%20%22Sammy%20has%20a%20balloon.%20The%20balloon%20has%20a%20ribbon%22%0Aprint%20balloon.sub(%22has%22%2C%22had%22)” message=”” highlight=”” provider=”manual”/]

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:

[pastacode lang=”ruby” manual=”balloon%20%3D%20%22Sammy%20has%20a%20balloon.%20The%20balloon%20has%20a%20ribbon%22%0Aprint%20balloon.gsub(%22has%22%2C%22had%22)” message=”” highlight=”” provider=”manual”/]

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:

[pastacode lang=”ruby” manual=”text%20%3D%20%22Sammy%20has%20a%20balloon%22%0Atext.gsub(%22ballooon%22%2C%20%22boomerang%22)%0Aprint%20text” message=”” highlight=”” provider=”manual”/]

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:

[pastacode lang=”ruby” manual=”text%20%3D%20%22Sammy%20has%20a%20balloon%22%0Atext%20%3D%20text.sub(%22ballooon%22%2C%20%22boomerang%22)%0Aprint%20text” message=”” highlight=”” provider=”manual”/]

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”:

[pastacode lang=”ruby” manual=”text%20%3D%20%22Sammy%20has%20a%20red%20balloon%22%0Atext.sub!(%22red%22%2C%20%22blue%22)%0Atext.sub!(%22balloon%22%2C%20%22boomerang%22)%0Aprint%20text” message=”” highlight=”” provider=”manual”/]

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:

[pastacode lang=”ruby” manual=”%22Sammy%20has%20a%20red%20balloon%22.gsub%20%2F%5Baeiou%5D%2F%2C%20%22%40%22″ message=”” highlight=”” provider=”manual”/] [pastacode lang=”ruby” manual=”%22S%40mmy%20h%40s%20%40%20r%40d%20b%40ll%40%40n%22″ message=”” highlight=”” provider=”manual”/]

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:

[pastacode lang=”ruby” manual=”%22Sammy%20has%20a%20red%20balloon%22.gsub%20%2F%5Baeiou%5D%2F%2C%20%7B%22a%22%20%3D%3E%20%22%40%22%2C%20%22o%22%20%3D%3E%20%220%22%7D%0A%23%20%22S%40mmy%20h%40s%20%40%20rd%20b%40ll00n%22″ message=”” highlight=”” provider=”manual”/]

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: