Strings Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

How can you substitute double quotation marks?

A

With %Q
e.g.
%Q(It’s Tuesday now.)
=> “It’s Tuesday now.”

%q substitutes single quotes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What do you use “casecmp” method for?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is string interpolation?

A

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!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What does the following code return?

a=”Xyzzy”

def my_value(b)
b[2] = '-'
end
my_value(a)
pus a
A

Xy-zy, because it is assigned to b[2] rather than b.

Numbers are immutable, strings are mutable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What does String#chars method do?

A
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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What does the following method definition validate?

def integer?(input)
/^\d+$/(input)
end

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you access the following string’s last character?

pet = “dog”

A

pet[-1]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is String#chop used for?

A

It removes the string’s last character unconditionally.

e.g.
name = “Craig”
name = name.chop

name
=> Crai

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What does String#chomp do?

A

It conditionally removes the tail end of a string (defaulting in a new line).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How does String#count work?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How does String#delete work (with examples)?

A

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”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly