String Flashcards

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

How to return the first or last symbol of a string?

A

‘string’[0] #=> ‘s’
‘string’[-1] #=> ‘g’
‘string’[1..-1] #=> ‘tring’

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

How to convert a string to an array of characters? 2 ways

A

‘hello’.chars #=> [“h”, “e”, “l”, “l”, “o”]

‘hello’.split(‘’) #=> [“h”, “e”, “l”, “l”, “o”]

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

How to find the number of a given character in a string?

A

‘hello’.count(‘h’) #=> 1

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

What is scan method?

A

Return an array of each matching of given expression

“A aaaa bb c”.scan(/[a-z]+/) #=> [“aaaa”, “bb”, “c”]

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

Why do we need format method? And how to use it?

A
puts format("A string %s, with minimum 10 signs %10s, with max 2 letters %.2s ", "hello",'dd', 'aaa')
#=> A string hello, with minimum 10 signs         dd, with max 2 letters aa
puts format("An integer: %i", 15)
puts format("A float: %f", 3.1415)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to calculate number/letter count in the string?

A

‘kdakdwa12345’.count ‘0-9’ #=>5

‘abc21321’.count ‘a-z’ # => 3

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

How to replace part of the string by regexp?

A
'hello a b c'.sub(/hello/, '\1 adwadwa')
# => " adwadwa a b c"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How to change string character case into opposite?

A
'daDSwa'.swapcase
# => "DAdsWA"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How to increment string in ruby? ( ‘Z01’ -> ‘Z02’)

A

str.succ

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

Why do we need to freeze string?

A

Strings in Ruby are mutable, which means you can change them. You can make a string immutable by using the freeze method. Trying to modify a frozen string will raise an exception.

str.freeze
str[0] = “”

RuntimeError: can’t modify frozen String

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

Why do ween need to freeze string?

A

It allows us to allocate space because the same frozen string use the same object id

a = 'hello'
b = 'hello'

different
p a.object_id
p b.object_id

a = 'hello'.freeze
b = 'hello'.freeze

the same
p a.object_id
p b.object_id

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

What is better to use symbol or string?

A

Symbol has better performance, so if it’s possible would be better to send symbols.

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

How to use multiline strings?

A
  1. here document or heredoc,
    hello = &laquo_space;DOC
    ddd
    ddd
  2. x = %q{This is a test
    of the multi
    line capabilities}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly