Ruby: Strings and Useful String Methods
String Interpolation
String interpolation is when a variable that stores a String is printed within another String. The variable is placed within #{ }
inside the quotes of the string, and the variable’s value will be printed. For instance:
Escape Characters in String Interpolation
Escape characters are preceded by a backslash \
and they “escape” being outputted in the ruby console. Examples of this are tabs \t
or line breaks \n
. They will output the whitespace left by a tab or a new line but will not be printed as "\t"
or "\n"
.
Line breaks are represented as \n
. They created a vertical whitespace of a new line between the two elements that the \n is situated.
String Concatenation
Strings can be concatenated using plus signs. For instance:
"Hello " + "how " + "are " + "you?"
becomes "Hello how are you?"
Ruby also uses the <<
to concatenate. This works like so:
“Hello” << “ Ruby”
becomes “Hello Ruby”
Converting to a String
The method .to_s
converts members of other classes to Strings. For instance 7.to_s
outputs as #=> "7"
.
All elements must be Strings to be concatenated so:
"Hey" + " m" + 8
will present an error, as a String and an Integer cannot be added, and must become "Hey" + " m" + 8.to_s
to be concatenated as "Hey m8"
.
Mutable and Immutable
Strings are mutable, which means that they can be changed. But what does that mean? When an instance of a string, e.g. "purple-people-eater"
, is created it has an object id number. If I was to create another "purple-people-eater"
string instance it would have a different object id number, even though it looks like the same string. This means that several instances of "purple-people-eater"
can exist at one time, and can all be modified and changed without affecting each other.
A Symbol however, :purple-people-eater
, can only exist as one instance at any given time. There cannot be multiple instances of the :purple-people-eater
and the instances cannot be modified. This is helpful in hashes where Symbols hold information. Information that the Symbol holds can be changed, without a new instance of the Symbol being created to hold the new value. This means information can be processed more quickly. This will become easier to understand when you have reached this post on hashes.
Some Useful String Methods