Chapter 7: Strings
A string is simply a list of characters, for example ‘hello world’ and ‘abcd’. The characters don’t necessarily have to mean anything. In real programs, you may use strings to insert and display text on the web page. Open any website. Whatever text you see there, it’s all made up of strings.
You can assign a string to a variable, as follows:
name = 'David'
framework = 'Ruby on Rails'
Here, we’re assigning the string ‘David’ to the variable name
and the second string ‘Ruby on Rails’ to the variable framework
.
You can use either single-quote ('
) or double-quote ("
) to declare strings. A major difference between the two is that the double-quotes let you insert a variable’s value inside the string. The following example should make it clear.
name = 'Akshay'
greeting = "Hello #{name}, how are you?"
print greeting # Hello Akshay, how are you?
Notice the special syntax around name
on line 2: #{name}
. When Ruby executes this line, it inserts the value of the name
variable into the string to generate the resulting string. This is called String Interpolation and it’s a pretty powerful and equally useful feature of Ruby.
There’re a few other differences between single and double-quoted strings, but we’ll ignore them for now.
What can you do with strings?
Strings are not simply a plain list of characters. You can perform various operations on them, such as calculate its length, convert the string to uppercase or lowercase, or combine multiple strings, and much more.
language = 'Ruby'
framework = 'Rails'
# check length of the string
print framework.length # 5
# change case
print language.upcase # RUBY
print language.downcase # ruby
# combine strings
sentence = language + framework # RubyRails
For a complete list of all the methods on strings, check out the String class. But you don’t have to memorize them all, as you read and write more and more Ruby programs, you’ll gradually become familiar with them.