获取字符串 class 调用的方法 - Ruby/Crystal
Get string class method called on - Ruby/Crystal
我一直在扩展 Crystal 中的字符串 class 以支持 "center" 方法。获取宽高的能力我已经做到了,其他大部分我都有。我只想要这个:
class String
def center
(I::Terminal.get_size.col / 2).times do #Half of screen width
print " "
end
#puts text that method was called on
end
end
puts "text".center #I want to puts "text" after my spacing
您不需要 times
块。您可以改用 String#rjust
。
此代码适用于 Ruby 和 Crystal
(假设你通过I::Terminal.get_size.col
整理出了终端宽度)
class String
def center(width = nil)
width ||= I::Terminal.get_size.col
half_width = (width / 2).to_i
half_size = (self.size / 2).to_i
self.rjust(half_width + half_size)
end
end
puts "this is a nice text".center 80
我注意到你将这个问题标记为 Crystal,但你问的是 Ruby/Crystal - 以防万一你正在使用 Ruby,知道你不需要它,因为it is already implemented.
我一直在扩展 Crystal 中的字符串 class 以支持 "center" 方法。获取宽高的能力我已经做到了,其他大部分我都有。我只想要这个:
class String
def center
(I::Terminal.get_size.col / 2).times do #Half of screen width
print " "
end
#puts text that method was called on
end
end
puts "text".center #I want to puts "text" after my spacing
您不需要 times
块。您可以改用 String#rjust
。
此代码适用于 Ruby 和 Crystal
(假设你通过I::Terminal.get_size.col
整理出了终端宽度)
class String
def center(width = nil)
width ||= I::Terminal.get_size.col
half_width = (width / 2).to_i
half_size = (self.size / 2).to_i
self.rjust(half_width + half_size)
end
end
puts "this is a nice text".center 80
我注意到你将这个问题标记为 Crystal,但你问的是 Ruby/Crystal - 以防万一你正在使用 Ruby,知道你不需要它,因为it is already implemented.