Table of contents
1.
Introduction
2.
Text
3.
String Operators
3.1.
“+” Operator
3.2.
“<<” Operator
3.3.
“*” Operator
3.4.
“%” Operator
3.5.
“+@” Operator
3.6.
“-@” Operator
3.7.
“=~” Operator
3.8.
“[]” Operator
3.9.
“[]=” Operator
3.10.
“ascii_only?” Operator
3.11.
Comparison Operators
4.
Frequently Asked Questions
4.1.
How do you assign a string in Ruby?
4.2.
Can you iterate over a string in Ruby?
4.3.
What is a range in Ruby?
4.4.
What is a nested hash?
4.5.
What are a truthy value and falsy value?
5.
Conclusion
Last Updated: Mar 27, 2024

String Operators in Ruby

Author Komal Shaw
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Ruby is the interpreted high-level programming language that supports various programming paradigms. It was designed with an emphasis on programming productivity and simplicity.

In Ruby, the String class is used to represent text. The String class contains several valuable operations for manipulating text strings. Ruby offers a variety of ways to express string literals in your code.

Text

The String class in Ruby is used to represent text. Strings are mutable objects, and the String class contains a collection of sophisticated operators and methods for extracting substrings, inserting and removing text, searching, and replacing, among other things. Ruby offers a variety of ways to express string literals in your code, and some of them include a sophisticated string interpolation syntax that allows the values of arbitrary Ruby expressions to be substituted into string literals.

Regexp objects represent textual patterns in Ruby, and Ruby gives a syntax for embedding regular expressions in your applications verbatim. For example, the code /[a-z]\d+/ denotes a single lowercase letter followed by one or more digits. Regular expressions are a frequent part of Ruby, although unlike numbers, texts, and arrays, regexps are not a basic datatype. 

String Operators

The String class contains several useful operations for manipulating text strings. 

“+” Operator

The “+” operator joins two strings together and returns a new String object:

planet = "Earth"
"Hello" + " " + planet

 

Output:

Hello Earth

 

Java programmers note that the + operator does not automatically convert its righthand operand to a string; you must do so yourself:

"Hello planet #" + planet_number.to_s  # to_s converts to a string

“<<” Operator

C++ programmers should be familiar with the “<<” operator, which appends its second operand to its first. This operator differs from + in that it modifies the lefthand operand instead of producing and returning a new object:

greeting = "Hello" 
greeting << " " << "World" 
puts greeting

 

Output:

Hello Earth

 

The operator, like +, does not convert the righthand operand's type. However, if the righthand operand is an integer, it is interpreted as a character code, and the appropriate character is attached. Only integers between 0 and 255 are allowed in Ruby 1.8. Any integer representing a valid codepoint in the string's encoding can be used in Ruby 1.9:

alphabet = "A" 
alphabet << ?B     # Alphabet is now "AB" 
alphabet << 67     # And now it is "ABC" 
alphabet << 256   # Error in Ruby 1.8: codes must be >=0 and < 256

“*” Operator

The righthand operand for the “*” operator is an integer. It returns a String that repeats the text supplied on the lefthand side as many times as the righthand side specifies.

"Ho! " * 3    #=> "Ho! Ho! Ho! "
"Ho! " * 0    #=> ""

“%” Operator

str is used as a format specification, and the result of applying it to arg is returned. If there are several substitutions in the format specification, arg must be an Array or Hash containing the values to be substituted.

"%05d" % 123                                            #=> "00123"
"%-5s: %08x" % [ "ID", self.object_id ]     #=> "ID   : 200e14d6"
"foo = %{foo}" % { :foo => 'bar' }              #=> "foo = bar"

“+@” Operator

Return a copied mutable string if the string is frozen.

Return the string itself if the string is not frozen.

“-@” Operator

Return the string itself if the string is frozen.

If the string isn't frozen, copy it, freeze it, and send it back.

“=~” Operator

If obj is a Regexp, use it as a pattern to match str, and return the point where the match begins, or nil if no match exists. Otherwise, it calls obj.= with str as the input. In Object, the default = yields nil. regexp = str is not the same as str = regexp. Only in the second scenario are strings acquired from designated capture groups allocated to local variables.

"cat o' 9 tails" =~ /\d/    #=> 7
"cat o' 9 tails" =~ 9       #=> nil

“[]” Operator

Returns a substring of one character at the given position if just a single index is provided. Returns a substring comprising length characters starting at the start index when given a start index and a length. The beginning and end of a range are understood as offsets delimiting the substring to be returned if one is given.

a = "hello there"
a[1]                    #=> "e"
a[2, 3]                #=> "llo"
a[2..3]                #=> "ll"

“[]=” Operator

Replaces part or all of str's content. The affected portion of the string is calculated using the same criteria as String#[]. The string will be changed if the replacement string is not the same length as the text it is replacing. IndexError is raised if the regular expression or string used as the index does not match a position in the string.

“ascii_only?” Operator

Returns true for a string that has only ASCII characters.

"abc".force_encoding("UTF-8").ascii_only?                  #=> true
"abc\u{6666}".force_encoding("UTF-8").ascii_only?   #=> false

Comparison Operators

The comparison operators == and != compare strings for equality and inequality, respectively. Two strings are equal if and only if they are the same length and contain the same number of characters. By comparing the character codes of the characters that make up a string, the operators,=, >, and >= compare the relative order of strings. The shorter string is smaller than the larger string if one string is a prefix of another. The comparison is only based on character codes. There is no normalization, and natural language collation order is ignored (if it differs from the numeric sequence of character codes).
 

String comparison is case-sensitive.

Keep in mind that uppercase letters have lower ASCII codes than lowercase characters. This means that "Z" is equivalent to "a."

Use the casecmp method to compare ASCII characters without regard to case, or convert your strings to the same case using the downcase or upcase methods before comparing them.
Check out this problem - Longest String Chain

Frequently Asked Questions

How do you assign a string in Ruby?

In Ruby, strings can be created by enclosing a sequence of characters in either single quotes' or double quotations ". You have the option of using single or double quotations.

Can you iterate over a string in Ruby?

To transform a string into an array of characters, use the chars method. Then you can iterate over this array by using each.

What is a range in Ruby?

A range is a type of object that has a starting and ending value and allows you to design sequences that span the entire range between these two values.

What is a nested hash?

We can use nested hashes to group or associate the data we're working with even more. They assist us in dealing with scenarios in which a category or piece of data is linked to a collection of values rather than a single discrete value.

What are a truthy value and falsy value?

In a boolean context, such as an if statement, it's a value considered True and false, respectively.

Conclusion

In this article, we have extensively discussed text and how to represent it using String Operators in Ruby.

We hope this blog has helped you enhance your knowledge regarding String operators in Ruby.

If you want to learn more, check out our articles on Ruby Programming LanguageRuby-DocumentationOfficial Ruby FAQ, and Learn Ruby.
 

Recommended problems -

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc.

Enroll in our courses and refer to the mock test and problems available.

Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow.

Happy Coding!

Live masterclass