Last active
January 10, 2021 23:20
-
-
Save dsasse07/5a19f6347ea79fa843c70c38d02e205f to your computer and use it in GitHub Desktop.
Creating a monkey patch to center align a string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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