...

/

Untitled Masterpiece

Learn to access the individual elements of a string.

Collection

A collection is a general term used to group multiple values into a single unit. We use collections all the time in the real world―a book is a collection of pages, a train is a collection of train cars, and a wardrobe is a collection of clothes.

String

A string is a collection of characters, mostly treated as a single unit. It is used to store text values like a name, address, message, etc.

Initializing the string

There are various ways to initialize a string in Ruby. The following program demonstrates these methods:

Ruby
String1 = 'String1 in Single Quotes \' not "'
print(String1,"\n")
String2 = "String2 in Double Quotes \" not '"
print(String2,"\n")
String3 = '''String3 in Three Single Quotes: neither \' nor "'''
print(String3,"\n")
String4 = '''String4 Three quotes
allow
multi-line'''
print(String4,"\n")

There are a few new things that we need to understand in the code above. The following are the three ways of initializing a string variable:

  • Line 1: The text of String1 is enclosed in single quotes ' '. Here, we can add directly and ' preceded by \ as part of the text.
  • Line 4: The text of String2 is enclosed in double quotes " ". Here, we can add ' directly and preceded by \ as part of the text.
  • Line 7: The text of String3 and String4 is enclosed in three single quotes ''' '''.
...