Get Substring in Ruby

Hassan Ejaz May 13, 2022
  1. the Substring Method in Ruby
  2. Extracting a Substring in Ruby
  3. Substring Removal or Replacement in Ruby
Get Substring in Ruby

A string carries an arbitrary sequence of bytes and operates on this sequence and is one of the basic elements of all programming languages. Being a part of the basic building of any program, one should have a grip on working with strings and know how to perform complex operations using strings.

We will introduce in this article how to create a substring from a string in Ruby with examples.

the Substring Method in Ruby

A substring is a range or specific array of characters taken from an existing string. Operating a substring is quite an appropriate approach when the user wants to work on a specific part of the string (like the initial, final, and middle part of the string).

There is no substring method in Ruby, and hence we rely upon ranges and expressions. If we want to use the range, we have to use periods between the starting and ending index of the substring to get a new substring from the main string.

We can also use commas(,) between 2 numbers only if we want to use the starting point of the substring. The second number will represent the number of elements we want to have in our substring from the starting point.

For a range example, let’s first examine the string a "virus", which has 5 characters from 0 to 4. If we want to get a substring in a reverse manner, we can use the negative end on a range, and we count backward from the length of the string.

Dots(.) can be used as the period characters in Ruby, and we can use the period characters within ranges. We can use 2 or 3 periods.

Unlike Python, we cannot use colons(:) inside the ranges. Instead, we can use period(.) ranges.

As shown below, let’s use the above scenario to get a substring in Ruby.

Code:

# ruby

StringForSub = "virus"

StartSub = value[0..3]
MidSub = value[2..3]
EndSub = value[3..-1]

puts StartSub
puts MidSub
puts EndSub

Output:

creating substrings from main string in ruby using indexing

The above output makes it easy to create substrings from the main string using the indexing method.

If we want to use commas(,) inside the ranges, we use 2 numbers. The first will be the starting point of the new substring, and the second number will be the length of the substring.

This next example uses the substring comma syntax in Ruby.

Code:

# ruby
mainString = "Ruby"

endSub = mainString[1,3]

puts endSub

midSub = mainString[1,2]

puts midSub

Output:

creating substrings from main string in ruby using comma

We can also use commas(,) inside the indexing method to get a range by providing start and ending values for our new substring.

Extracting a Substring in Ruby

Any malicious code can be avoided by locating and sanitizing input from users by locating a specific substring among strings. A substring can be located by using different methods such as:

  1. Ruby include?() method.
  2. RegEx method.
  3. Ruby String Element Reference [].

the Ruby include?() Method

This built-in method is the easiest method to locate a substring.

Let’s have an example in which we will use a string as information input by the user. To check if the content contains any spam element or not.

# ruby
mainStr = 'User submitted this content. It is a spam'
 if mainStr.include?("spam")
   puts "Spam Content! Content Deleted"
 else
   puts "Content Saved"
 end

Output:

checking substring in a main string using ruby

It can detect the substring from the main string, but one thing to remember is that it is a case-sensitive method.

Since the method’s return value is a Boolean value (true or false) indicating if the substring is available or not, respectively; therefore we implement an if-else statement to act accordingly.

A disadvantage of using the include? method is that it is case-sensitive, and spam can return a false statement. It is essential to convert the whole string into uppercase or lowercase and then locate a specific substring within a string.

The method is as follows to convert into uppercase.

Code:

# ruby
mainStr = 'User submitted this content. It is a SPAM!'
 if mainStr.include?("spam".upcase)
   puts "Spam Content! Content Deleted"
 else
   puts "Content Saved"
 end

Output:

checking substring in a main string using ruby with uppercase method

Let’s imagine the same scenario, but we have to use the lowercase.

Code:

# ruby
mainStr = 'User submitted this content. It is a SPAM!'
 if mainStr.include?("spam".downcase)
   puts "Spam Content! Content Deleted"
 else
   puts "Content Saved"
 end

Output:

checking substring in a main string using ruby with uppercase method

As you can see, we can use substrings to make our system secure by checking for the substrings from the submitted data for spam or some other type of content that we don’t want to be saved inside our application.

the RegEx Method in Ruby

Ruby returns nil using this method if the specific substring is not found within the string. In this method, a simple regular expression is used to check if the string the specified regular expression pattern spam.

Code:

# ruby
mainStr = 'User submitted this content. It is a spam!'
puts mainStr =~ /spam

Output:

regex method in ruby

We can also find the required substring from a string using the RegEx method and return the substring’s location inside a string. If the substring isn’t found, it will return nil.

String Element Reference [] Method in Ruby

The Ruby string reference method passes either a string, an index value, or a regular expression inside a pair of square brackets.

Code:

# ruby
mainStr = 'spam'
puts mainStr['spam']
puts mainStr['[not-spam]']

Output:

using element ref in ruby

It returns the original string if the checking substring is present inside the main string, or it will return nil if the substring is not present inside the main string.

For regular expressions:

# ruby
mainStr = 'spam'
puts mainStr[/spam/]

Output:

using element ref in ruby

Substring Removal or Replacement in Ruby

If there is a need to replace or remove a certain substring from the main string, we can use the simple assigning method. We can use the index method to change the value.

Code:

# ruby
mainStr="Hello World!"

mainStr[0..4] = "Bye"

puts mainStr

Output:

replacing substring using the index method

Use the indexing method to replace or remove a certain part of the main string by just assigning the value to the part of the string.

Related Article - Ruby String