CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

Ruby Programming – Built-in Classes – String class

Everything is an object in Ruby. That means each symbol or variable you create must be an object of a Class. For example, if you type the string “Hello!”; that must be an object of the String class. Don’t you believe it? Here is an example.

"Hello!".class

You will see the class name String will be displayed on the screen; once you run the above statement with Ruby. Have we defined this Class? No. But why it is showing String as the class name? This is where built-in or standard classes come into the picture.

Ruby provides some built-in classes to make our job a bit easy. Through this Article, we are going to discuss the String class; one of the built-in classes.

Strings in Ruby are sequences of characters; enclosed either in single quotes (‘) or in double quotes (“).

Creating String objects

Ruby allows to the creation of String objects in different ways. If you specify the string in quotes (‘ or “); Ruby automatically creates an object for you.

str = "Ruby is simple and easy to learn"
str.class

Here str is the String object.

Another way of creating a String object is by using the String class. Using class’s new method allows the creation of the object of the class.

str = String.new

The above statement creates a String object and assigns it to the str variable. This creates an empty string. If you want to add some data to it; you can pass the text as an argument. Here it looks like this;

str = String.new ("Good day!")

Accessing String elements

The string is a collection of characters. We can access the characters from the String using their index values. The starting index is “0”. For example, from above; str[0] gives the first character from the string; which is “G”.

Escape Characters

Strings support escape characters. You can specify them by prefixing the backslash (“\”) symbol. Examples of escape characters are “\n”, “\t”, “\\” etc,. We can use these characters in Strings.

There is an important thing you need to remember here; when the string is enclosed within single quotes (‘); it supports only “\\” and “\'” escape characters. These are backslash and single quote symbols. Other escape characters will print as it is. Got confused? Here is an example;

'What\'s your name?'
'Hello!\nGood day!'

Have you observed the difference? These strings are enclosed in single quotes (‘); as discussed above, only “\\” and “\'” escape characters can be converted and all other escape characters will print as it is. Hence “\n” was not converted to a new line; instead, it prints as it is.

When you enclose the strings in double quotes (“); you can use all the escape characters. See the difference below example;

"WoW!\nWonderful!"

| Nick |

Ruby Programming – Built-in Classes – String class

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top