Strings Flashcards
How can you substitute double quotation marks?
With %Q
e.g.
%Q(It’s Tuesday now.)
=> “It’s Tuesday now.”
%q substitutes single quotes
What do you use “casecmp” method for?
To compare the value of two strings while ignoring the case of both strings.
e.g.
name = ‘Roger’
puts name.casecmp(‘RoGeR’) == 0
puts name.casecmp(‘DAVE’) == 0
true
false
What is string interpolation?
Invoking a variable (or a method) withing a string and Ruby automatically calls #to_s on the value.
e.g.
name = ‘Tom’
puts “Hello #{name}!”
=> Hello Tom!
What does the following code return?
a=”Xyzzy”
def my_value(b) b[2] = '-' end my_value(a) pus a
Xy-zy, because it is assigned to b[2] rather than b.
Numbers are immutable, strings are mutable
What does String#chars method do?
It returns an array of characters. e.g. def sum(num) num.to_s.chars end
puts sum(496) => ["4", "9", "6"]
Firstly convert a number to a string and then we created an array of characters.
Obviously it works directly on strings.
What does the following method definition validate?
def integer?(input)
/^\d+$/(input)
end
It validates if the input is an integer or not.
^ means start of string
\d means regex to test against digits
+ means one or more (of the preceding matcher)
$ means end of string
How do you access the following string’s last character?
pet = “dog”
pet[-1]
What is String#chop used for?
It removes the string’s last character unconditionally.
e.g.
name = “Craig”
name = name.chop
name
=> Crai
What does String#chomp do?
It conditionally removes the tail end of a string (defaulting in a new line).
How does String#count work?
It gives as the number of characters we asked it to count.
e.g.
a = “danish banana”
a.count (“n”) => 3
a.count (“an”, “n”) =>3
(It only counts the intersection of the two strings)
a.count (“a-d”) => 6
How does String#delete work (with examples)?
It deletes whichever characters we assign to it.
e.g.
a = “danish banana”
a.delete (“a-d”) => “nish nn”
a. delete (“an”) => “dish b”
a. delete (“an”, “n”) => “daish baaa”