Skip to content

Instantly share code, notes, and snippets.

@dsasse07
Last active January 10, 2021 23:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsasse07/5a19f6347ea79fa843c70c38d02e205f to your computer and use it in GitHub Desktop.
Save dsasse07/5a19f6347ea79fa843c70c38d02e205f to your computer and use it in GitHub Desktop.
Creating a monkey patch to center align a string
require 'tty-screen'
class String
def center_align
screen_width = TTY::Screen.width
screen_center = screen_width / 2
string_length = self.length
string_center = string_length/2
offset = screen_center - string_center
"#{sprintf("%#{offset}s" % self)}"
end
end
puts "Hello World!".center_align
#=> Hello World
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment