📄 string_extension.rb
字号:
class String
# If length is greater than the self.lenth, returns a new String, it's length equals to +length+,
# content is distributed center, padded with +padstr+; otherwise, returns self.
# Example
# - "ab".distribute_center(1,'.') #=> "ab"
# - "ab".distribute_center(2,'.') #=> "ab"
# - "ab".distribute_center(3,'.') #=> "ab."
# - "ab".distribute_center(4,'.') #=> ".a.b"
# - "ab".distribute_center(5,'.') #=> ".a.b."
# - "ab".distribute_center(6,'.') #=> ".a.b.."
# - "ab".distribute_center(7,'.') #=> "..a..b."
# - "ab".distribute_center(8,'.') #=> "..a..b.."
# - "ab".distribute_center(9,'.') #=> "..a..b..."
# - "ab".distribute_center(10,'.') #=> "...a...b.."
# - "ab".distribute_center(11,'.') #=> "...a...b..."
def distribute_center(length, padstr=' ')
return self if length <= self.length
# e.g "ab".distribute_center(10)
spaces_count_toadd = length - self.length # will be 10-2=8 <-> "123a456b78"
points_count_toinserted = self.length+1 # will be 2+1 = 3 <-> "1a2b3"
space_count_everypoint_toadd = (spaces_count_toadd*1.0/points_count_toinserted).round
result = ""
(0..self.length-1).each do |i|
result << "".center(space_count_everypoint_toadd, padstr) + self[i,1]
end
return result.ljust(length, padstr)
end
end
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -