Last active
October 16, 2018 07:42
-
-
Save tkfm-yamaguchi/c7306a0bee4a992139f3cc5bdac00571 to your computer and use it in GitHub Desktop.
ruby's string class extension conting the length of multi-byte string as 2
This file contains 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
class String | |
# number of characters where the multi-byte string is counted by 2 | |
def mbsize | |
chars.sum{|str| str.bytesize == 1 ? 1 : 2 } | |
end | |
def mbljust(num, char=" ") | |
return self if mbsize > num | |
self + char * (num - mbsize) | |
end | |
def mbrjust(num, char = " ") | |
return self if mbsize > num | |
char * (num - mbsize) + self | |
end | |
def mbcenter(num, char = " ") | |
return self if mbsize > num | |
padsize = num - mbsize | |
half = char * (padsize / 2) | |
padded = half + self + half | |
padsize.even? ? padded : padded + char | |
end | |
end | |
p "北海道".mbljust(11) | |
p "会津若松市".mbljust(11) | |
p '🐧🐰'.mbljust(11) | |
p '🐧🐰'.mbrjust(11) | |
p '🐧1🐰'.mbcenter(11) | |
p '1'.mbcenter(11) | |
# => | |
# "北海道 " | |
# "会津若松市 " | |
# "🐧🐰 " | |
# " 🐧🐰" | |
# " 🐧1🐰 " | |
# " 1 " |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment