當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Ruby String center()用法及代碼示例

center是Ruby中的String類方法,用於將給定字符串的寬度居中。如果指定的寬度大於給定字符串的長度,則此方法將返回指定寬度的新字符串,其中給定字符串居中並填充,否則將僅返回給定字符串。

用法:
str.center(width, padstr='')->new_str

參數:此處,str是給定的字符串,而width是用於將字符串居中的指定寬度。


返回值:此方法可以返回新的修改後的字符串new_str或相同的字符串。

示例1:

#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)

輸出:

String
     Methods

示例2:

#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')

輸出:

45Ruby456
789String Class789


相關用法


注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 Ruby | String center() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。