Skip to content

Latest commit

 

History

History
104 lines (104 loc) · 1.92 KB

string_methods.md

File metadata and controls

104 lines (104 loc) · 1.92 KB
String Length
"Turing".length or "Turing".size
#6
Checking if string is empty
"Turing".size == 0
#true
"".empty?
#true
Reversing string
"Turing".reverse
# “gniruT”
Upcasing string
"Turing".upcase
# “TURING”
Downcasing string
"TURING".downcase
# “turing”
Captializing string
"turing".capitalize
# “Turing”
If a string contains another string
"Turing".include? "z"
# equals to false because there is no z in Turing
Returns a copy of string with all occurrences of pattern substituted for the second argument
"Turing".gsub!(/[ri]/, "z")
# Tuzzng
Transform string to integer
"1".to_i
#1
Transform string to symbol
"turing".to_sym or "turing".intern
#:turing
Transform symbol to string
:turing.to_s
#"turing"
Convert a string to an array of characters

can pass argument into this method to specify a different separator

"turing".split
#['t', 'u', 'r', 'i', 'n', 'g']
Convert an array to a string
turing_array = ['t', 'u', 'r', 'i', 'n', 'g']
turing_array.join
# "turing"
Iterate Over Characters Of a String in Ruby
string = "turing"
string.each_char { |letter| puts letter }
#t
#u
#r
#i
#n
#g
String interpolation

allows you to combine strings together

name = "Turing"
puts "#{name} is life!"
# "Turing is life!"
Padding a string

takes two arguments: first argument is length of final string second argument is what string will be padded with

binary_string = "1111"
binary_string.rjust(7, "0")
# "0001111"

if you want to pad to the right you can use ljust

binary_string = "1111"
binary_string.ljust(7, "0")
# "1111000"