String Formatting
This was the tip of the week in the July 1, 2021 Ruby Weekly Newsletter.
We often need to format strings to appear a certain way. This week, we’ll cover several formatting and minor manipulation methods on Strings:
-
String#ljust
andString#rjust
both take an integer argument, and an optional padding argument. If the length of the string is smaller than the integer, they’ll return a new string of the length of the integer, padded with the padding argument repeated to fill the space, or spaces (String#ljust
padds on the right of the string, andString#rjust
pads on the left:"This string needs a length of 35".ljust(35, "asdf") => "This string needs a length of 35asd" "This string is already longer than 35".ljust(35) => "This string is already longer than 35"
-
String#center
behaves the same asString#ljust
andString#rjust
except it pads on both sides (with extra padding on the right in the case of an odd number of padding characters):"String".center(10) => " String "
-
String#delete_prefix
takes a parameter of the prefix to delete, and does exactly what it claims. It is also faster thanString#sub
orString#gsub
:"id_12345".delete_prefix("id_") => "12345"
If the prefix doesn’t exist, it will return the original String:
"12345".delete_prefix("id_") => "12345"
-
String#delete_suffix
works just likeString#delete_prefix
except it deletes from the end of the string:"uploaded_image_12.pdf".delete_suffix(".pdf") => "uploaded_image_12"