Ruby String Datatype
Strings can be formed in ruby using single quotes
or double quotes
.
Any characters such as number or alphabets or symbols enclosed within quotes are Strings
.
We've already learnt about adding newline character to a string. Likewise, other characters can also be embedded in strings.
name = "Bharath\tKumar"
\t
adds tab space
\s
adds space
For creating strings, this is an added advantage of using double quotes over single quotes. If you use double quotes, you could use single quote as apostrophe
in the string.
str = "Bharath's"
- But you cannot use single quote directly inside single quotes.
- But there is a way to do so, using a special character
\
which acts as the escape character, hence telling the compiler/interpreter that the next character has some special meaning, as in case of \n
. In other cases, like for apostrophe, the backslash \
tells the compiler/interpreter that the following character has no special meaning and that the following character is to be part of the string.
str = 'Bharath\'s'
Use \'
inside double quotation to include apostrophe in string.
In the below image, when using a single quote inside the string's single quotes, you can see that we aren't able quit the interactive mode. So, it's not advisable.
Ruby: HERE Keyword
To create a multiline string and store it in a variable HERE
keyword is used.
This begins with a two less than symbols <<
and the keyword HERE indicates that, until you see the keyword HERE again, store all the values in the variable.
quote = << HERE
What you do
today can
improve
all your
tomorrows
HERE
So, the value What you do\ntoday can\nimprove\nall your\ntomorrows
is stored in the variable quote
. This is the easiest way to store large fragments of text in the variable.
Ruby: Split method
Split is a useful method for taking the string and splitting into parts. Its syntax is :
<String Value>.split(<DELIMITER>)
Where, the delimiter is the point from where the string specified will be split into two.
first,last = "Bharath,Kumar".split(/,/)
Here comma (,)
is the delimiter. We use slashes (/)
to delimit(escape) the delimiters.
When this statement is executed, the piece of text before comma is assigned to the variable first and the piece of text after comma is assigned to the variable last.
Therefore in the picture above, value Bharath
is assigned to the variable first
and value Kumar
is assigned to the variable last
.
Ruby: Squeeze method
Squeeze
is used to remove trailing spaces from the string. Following is the syntax for it :
<String Value>.squeeze
In the above image, you could note the number of spaces in the variable first. When printing the first variable using squeeze method it removes the trailing spaces.