Blog
Ruby Programming Series Chapter 3 Strings
- January 31, 2017
- Posted by: admin
- Category: Programming Ruby Basics

Strings
A string holds sequence of characters in ruby program. These can be letters, numbers or special characters written inside a pair of either single quotes (”) or double quotes (“”). Using double quotes is the preferred way of working with strings. In a program string values are assigned to a variable.
name = "The Dark Knight" director = "Christopher Nolan" summary = "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice." famous_quote = "\"We stopped looking for monsters under our bed, when we realized they were inside us\", said the Jocker."
As you can obverse in the above we have used \ in 2 places, this is known as an escape character. We are telling ruby interpreter that “(double quote) is part of the string and not to treat it as the end of string.
Give it a shot
Try removing both the \ characters in the string and run the program.
String Interpolation
When we want to display the value of a variable inside a string or perform some ruby operation we make use of string interpolation.
Let us create a variable called actor and give it a value
actor = "Christian Bale"
Now let us try displaying the name of the actor inside a string
puts "The lead actor of Dark Knight movie is actor."
We get the output as
=> The lead actor of Dark Knight movie is actor.
Here the variable is treated just like another character of the string. If you want the display the value of the variable, then we need to perform string interpolation like
To use string interpolation we make use of #{} inside a double quoted string.
puts "The lead actor of Dark Knight movie is #{actor}."
Now we get the output as
=> The lead actor of Dark Knight movie is Christian Bale.
The above operation can also be performed as string concatenation like the way we did in the previous chapter, but string interpolation makes it easier to code and interpret the statement.
Another Example
running_time = 128 puts "Total duration of the movie is #{running_time/60} hrs and #{running_time % 60} mins"
Can you guess what the output is going to be?
String Methods
There are plenty of methods built into ruby language to adds behavior to strings like
city = "gotham" genre = "action, drama, thriller" city.capitalize # => "Gotham" city.upcase # => "GOTHAM" city.downcase # => "gotham" city.reverse # => "mahtog" city.length # => 6 genre.split(', ') # => ["action", "drama", "thriller"]
[…] Next Chapter : Strings […]