Week: 03/05/2023 - 03/11/2023
Working with Strings in Ruby
Input:
'Single quoted strings #{represent} "characters" verbatim.'
Output:
Single quoted strings #{represent} "characters" verbatim.
Input:
"Double-quoted strings make some substitutions: #{2 + 4}"
Output:
Double-quoted strings make some substitutions: 6
To join Strings, you can interpolate or concatenate
-
String concatenation
- joining of strings
- can join strings together using
""
and+
between strings - you have to add
" "
, an empty string with a space to prevent two words being put together -
myvar
can be a variable inserted with a string and can add other strings with the plus sign+
- if you do
+=
the myvar will be have the new concatenation as the new string - strings can only be concantenated with other strings
-
String interpolation
- interpolation
#{}
can be used within double quoted strings and it will substitute the result of a ruby code into the middle of the string - the interpolation will be evaluated and the result will be converted into a string
- interpolation
Interactive Ruby (irb)
- can use IRB (interactive ruby) which is integrated in Ruby if you type "irb" and hit return in terminal
- irb will show you the result of each expression, you dont need to call "puts" or anything
- type "exit" and then enter to exit out of IRB
p vs puts vs print method
- Ruby provides a method
p
which is different thanprint
andputs
- p method allows us to inspect the values we pass to it and to print them out approximate the same way they would appear in a ruby code
Input: puts
puts " "
puts ""
puts nil
puts []
The output is an empty terminal
Input: print
print " "
print ""
print nil
print []
The output is []%
Input: p
p " "
p ""
p nil
p []
The output is:
" "
""
nil
[]
Some escape sequences
- \n skips to a new line
- \t indents a text
- \" inserts "double quotes"
- \' inserts 'single quotes'
- \ inserts a backslash: \
Input: example
puts "first line
second line"
puts " new paragraph"
puts " He said, "Whoa.""
to fix the line above use escape sequences
puts "first line\nsecond line"
puts "\tnew paragraph"`
puts "He said, \"whoah\""
Next Week: Ruby Objects
Top comments (0)