Ruby Intro - Strings Flashcards
Either double or single quotes can be used to protect text. Why would you use one over the other?
To include quotation marks as strings into your text (you’d need to use the single quotes then).
What’s the rule using escape characters or string interpolation with quotes?
Escape characters and string interpolation work within a double quoted string but not within single quoted string. For instance /n creates a new line, but only in a double quoted string.
What is best way to protect strings with lots of escape characters and quotes.
Use double quotes to protect the string. Then use escape characters each time to show any quote whatsoever.
Is interpolation or concatenation better to build up multiple strings together?
Usually interpolation
What is String Interpolation? Give an example.
Putting a string inside a string. Inside the #{}, you place ruby code; the code is executed, and the return value is inserted inside the string.
worst_day = “Monday”
"#{worst_day}s are the hardest." # => "Mondays are the hardest."
What’s the readability rule when using String Interpolation
The code inside the #{} should be very short; just one variable plus maybe a single method call. Otherwise, first save the result in a temporary variable, then interpolate that:
MURDER = “redrum”.reverse.upcase
”#{MURDER}! #{MURDER}!”
How do you append strings to strings? Two methods, Code examples.
count_in = “”
count_in «_space;“One, “
count_in «_space;“two, “
# …
count_in = "" count_in = count_in + "One, " count_in = count_in + "two, " # ...
How do you find out what substring is in what specific position/index of your code?
"this is my sentence"[5..6] # => "is"
How do you find character length of a string? code
"words words words".length # => 17
If you wanted to split up a string, what would you want to do first? How would you code it?
=> [“Bi-Rite”, “Humphrey Slocum”, “Mitchell’s”]
You would want to split the string up into an ARRAY of split elements.
ice_creams = “Bi-Rite, Humphrey Slocum, Mitchell’s”
ice_creams.split(“, “)
How do you purge string or create empty string via code (not using “ “)?
nil.to_s
=> “”
The methods for removing returns and leading and trailing spaces in a string?
chomp and #strip (#chomp! and #strip!)
What method for find and replace type function on a new copy of a string?
gsub (#gsub! not a copy)
Syntax for gsub for string replacement?
gsub(pattern,replacement)
"hello".gsub(/[aeiou]/, '*') #=> "h*ll*"
"hello".gsub(/[eo]/, 'e' => 3, 'o' => '*') #=> "h3ll*"
Syntax for gsub for hash?
gsub(pattern,hash)
"hello".gsub(/[aeiou]/, '') #=> "hll"