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 and String#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 ( ) if no argument is passed. String#ljust padds on the right of the string, and String#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 as String#ljust and String#rjust except it pads on both sides (with extra padding on the right in the case of an odd number of padding characters):

      => "  String  "
  • String#delete_prefix takes a parameter of the prefix to delete, and does exactly what it claims. It is also faster than String#sub or String#gsub:

      => "12345"

    If the prefix doesn’t exist, it will return the original String:

      => "12345"
  • String#delete_suffix works just like String#delete_prefix except it deletes from the end of the string:

      => "uploaded_image_12"