红宝石 |字符串中心()方法
center是 Ruby 中的 String 类方法,用于将给定字符串的宽度居中。如果指定的宽度大于给定字符串的长度,则此方法将返回指定宽度的新字符串,给定字符串居中并填充,否则仅返回给定字符串。
Syntax:
Parameters: Here, str is the given string and width is the specified width used to center the string.
Returns: This method can either return a new modified string new_str or the same string.
示例 1:
str.center(width, padstr='')->new_str
输出:
#ruby 2.3.1
# Ruby program to demonstrate
# the center method
# Taking a string and
# using the method
puts "String".center(5)
puts "Methods".center(18)
示例 2:
String
Methods
输出:
#ruby 2.3.1
# Ruby program to demonstrate
# the center method
# Taking a string and
# using the method
puts "Ruby".center(9, '456')
puts "String Class".center(18, '789')