String Flashcards
How to return the first or last symbol of a string?
‘string’[0] #=> ‘s’
‘string’[-1] #=> ‘g’
‘string’[1..-1] #=> ‘tring’
How to convert a string to an array of characters? 2 ways
‘hello’.chars #=> [“h”, “e”, “l”, “l”, “o”]
‘hello’.split(‘’) #=> [“h”, “e”, “l”, “l”, “o”]
How to find the number of a given character in a string?
‘hello’.count(‘h’) #=> 1
What is scan
method?
Return an array of each matching of given expression
“A aaaa bb c”.scan(/[a-z]+/) #=> [“aaaa”, “bb”, “c”]
Why do we need format method? And how to use it?
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 to calculate number/letter count in the string?
‘kdakdwa12345’.count ‘0-9’ #=>5
‘abc21321’.count ‘a-z’ # => 3
How to replace part of the string by regexp?
'hello a b c'.sub(/hello/, '\1 adwadwa') # => " adwadwa a b c"
How to change string character case into opposite?
'daDSwa'.swapcase # => "DAdsWA"
How to increment string in ruby? ( ‘Z01’ -> ‘Z02’)
str.succ
Why do we need to freeze string?
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
Why do ween need to freeze string?
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
What is better to use symbol or string?
Symbol has better performance, so if it’s possible would be better to send symbols.
How to use multiline strings?
- here document or heredoc,
hello = «_space;DOC
ddd
ddd - x = %q{This is a test
of the multi
line capabilities}