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? Here it 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 comes into the picture.

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

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

Creating String objects

Ruby allows to create 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 String class. Using class’s new method allows to create the object of the class.

str = String.new

Above statement, creates a String object and assign 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;

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

Accessing String elements

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 back slash (“\”) symbol. Example 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 with in 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 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 with below example;

"WoW!\nWonderful!"

| Nick |

Add a Comment

Your email address will not be published.