Work with String Methods in Ruby
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:
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:
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:
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:
The [ ] syntax is AN alias for the slice, therefore you’ll treat strings like arrays:
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:
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:
Now, let’s convert the string to be all lower case:
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:
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:
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:
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:
You will use downcase!, upcase!, capitalize! and swapcase! to switch the first string instead:
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:
You will specify a string because of the second argument if you wish to use a distinct character:
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:
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:
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:
This is particularly helpful for removing the newline character (\n) from strings:
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:
If you do not specify a string to get rid of, chomp can take away the newline:
However, if the string does not contain a newline character, chomp simply returns the first string:
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:
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:
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:
The index methodology solely finds the primary occurrence tho’. Here’s AN example with an extended string:
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:
The start_with? methodology accepts multiple strings and returns true if any of them match:
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?:
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”.
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:
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:
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:
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:
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”:
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:
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:
You will use this to perform a lot of advanced substitutions with less code.
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.