Qiuliang's Site

做一个独立思考和具备创新能力的人,打造谦逊和强大的内心

【Ruby on Rails】Advanced Ruby String Tips

ord将字符转换为ASCII编码

?B.ord
# => 66

chr将ASCII编码转换为字符

66.chr
# => B

split将字符串分割为数组

"I love Ruby Programming".split(' ')
# => ["I","love","Ruby","Programming"]

split配合uniq后并去重

"aabbcc".split('').uniq
# => ["a","b","c"]

配合sort进行排序,按ASCII编码大小

"I love Ruby Programming".split('').uniq.sort

scan从字符串中查找匹配的字符,返回数组

"Everybody loves Ruby".scan(/[a-m]/)
# => ["e", "b", "d", "l", "e", "b"]

gsub该函数的作用是使用正则替换掉字符串中匹配的值。变量调用gsub方法后,变量本身不改变,如果需要改变,可在方法后加!

a = "test1";
b = a.gsub(/\d+/,'a');
print a;
print b;
a.gsub!(/\d+/,'b');
# a => test1
# b => testa
# a => testb

提取字符串中的数字,并乘以2后替换:

"I am 18 years old.".gsub(/\d+/){2*$&.to_i}
# I am 36 years old.

提取字符串中的单引号和双引号,加上斜杠后替换:

str = %q(Ruby said, "Don't you like Ruby"); str.gsub(/['"]/) {'\\'+$&}
# Ruby said, \"Don\'t you like Ruby\"

重复输出字符串N次:

"hello" * 10;

capitalize将字符串首字母大写:

"hello".capitalize
# Hello

chop去掉末尾的一个字符:

"hello".chop
# hell

next将字符串末尾的一个字符替换为下一个字符,例如“a”替换为“b”,“1”替换为“2”,如果是非字母或数字的字符,则替换前一个。

"hello".next
# hellp

swapcase将字符串中的字母大小写反转替换。

"Hello".swapcase
# hELLO