String几乎是所有面向对象编程语言中最常用的类了,在ruby中也不例外,下面是几个在ruby中String的常用方法,记录下来。
concat:连接2个字符串,样例:
<span style="font-family:SimSun;font-size:18px;">puts "Hello ".concat("world!")</span>
输出:Hello world!
capitalize:连首字母大写,其他字母小写,样例:
<span style="font-family:SimSun;font-size:18px;">puts "hello World!".capitalize()</span>
输出:Hello world!
downcase:转为小写,样例:
<span style="font-family:SimSun;font-size:18px;">puts "Hello World!".downcase()</span>
输出:hello world!
upcase:转为大写,样例:
<span style="font-family:SimSun;font-size:18px;">puts "Hello World!".upcase()</span>
输出:HELLO WORLD!
swapcase:大小写反转,样例:
<span style="font-family:SimSun;font-size:18px;">puts "hello".swapcase()</span>
输出:HELLO
chop:删除末尾的字符,样例:
<span style="font-family:SimSun;font-size:18px;">puts "Hello world".chop()</span>
输出:Hello worl
hash:获取hash值,样例:
<span style="font-family:SimSun;font-size:18px;">puts "Hello World!".hash()</span>
输出:-224243329
next:最后一个字符加一,样例:
<span style="font-family:SimSun;font-size:18px;">puts "Hello World".next()</span>
输出:Hello Worle
reverse:反序,样例:
<span style="font-family:SimSun;font-size:18px;">puts "hello".reverse()</span>
输出:olleh
sum:对每个字符对应的值求和,样例:
<span style="font-family:SimSun;font-size:18px;">puts "hello".sum()</span>
输出:532