Learning Ruby - Numbers, Strings, and Additions
Strings are a collection of characters. Anything you type with your keyboard is a character.
Type the following into the SANDBOX:
puts "Ruby is cool" puts "Models, Views & Controllers" name = "Bob" puts name + " " + "Smith" puts "123" puts "23" + "15"
Numbers vs. Strings and "addition"
Notice that when we use the + operator with strings the two strings are smooshed together. We call that string concatenation.
This is true whether the string contains letters or numbers. That is, there's a difference between the number 5 and the string "5".
Although a human sees the obvious relationship between these two symbols, a computer doesn't. 5 and "5" are as different to a computer as 5 and "cat". So when we "add" two strings using + we don't get number-wise addition but instead get string-wise addition.
Per above, we call string-wise addition concatenation.
The * symbol can also be used with strings, but since * is just repeated addition, we get repeated concatenation.
# This is equivalent to: # puts "Hello" + "Hello" + "Hello" + "Hello" puts "Hello" * 4 # This is equivalent to: # puts "234" + "234" + "234" puts "234" * 3
There are also special characters that can be used in strings by using the escape character or backslash \.
sentence1 = "This is a newline \n it puts strings on a new line" puts sentence1 sentence2 = "\"These double quotes are escaped\", he explained." puts sentence2 sentence3 = "Even the backslash ( \\ ) is escaped." puts sentence3
There are many built-in methods available for strings in the Ruby language. Let's look at a few by typing each line below into the SANDBOX:
puts "this is fun".reverse words = "i like to code" puts words.upcase puts words puts "---" puts words.upcase! puts words puts "---" puts words.match("LIKE") puts words.match("LIKE").inspect puts words.match("like").inspect # notice how match is case-sensitive