1.1 String Basics

String Interpolation

It is essential to be able to replace placeholders within a string with values they represent. In the programming
paradigm, this is called "string interpolation". In Ruby, string interpolation is extremely easy.
Feel free to run the example below to see the sample in action.

Hint

Output Window

We've been using double quotes in all our string interpolation examples.
A String literal created with single quotes does not support interpolation.

The essential difference between using single or double quotes is that double quotes allow for
escape sequences while single quotes do not. What you saw above is one such example.
“\n” is interpreted as a new line and appears as a new line when rendered to the user, whereas
'\n' displays the actual escape sequence to the user.

Let us move on...

Search in a String

Another common scenario is checking if a String contains any given character, word or
sub-string. Considering your experience with the Ruby API and its intuitiveness, try and
check whether the String given below includes 'Yoda'.

Hint

Output Window

Hint

String#end_with?

Output Window

Are you getting the hang of the Ruby API? The previous three methods all ended with a '?'.
It is conventional in Ruby to have '?' at the end of the method if that method
returns only boolean values. Though it is not mandated by the syntax, this practice is
highly recommended as it increases the readability of code.

Sometimes we will be required to know the index of a particular character or a sub-string
in a given String and conveniently Ruby provides a method on String that does exactly that. Try and
find out the index of 'R' in the string below:

Hint

String#index

Output Window

String case change

The last thing we will look into in this lesson is manipulating
the case of strings. Ruby provides us with a convenient tool-set to take care of proper
and consistent casing within strings. Let's start with converting a string in lower case to upper case.

Hint

Output Window

Hint

String#downcase

Output Window

On a parting note, let us touch on an interesting method. When you
encounter a mixed cased string, Ruby provides a way to swap the case of every character in it i.e. this method would convert "I Am MixEd" to "i aM mIXeD".
Try to figure this method out and tell us if you ever come across a scenario where
you find use for this. It might make a good story for a rainy night!