1、字符串定义与产生
str1 ='Hello world'
str2 ="Hello world"#双引号比单引号定义的字符串更加强大,如可提供转移字符等
str3 =%q/Hello world/# %q将后面的字符串转换成单引号字符串,后面的/为自定义的特殊符号,在字符串结尾处也需有该特殊符号
str4 =%Q/Hello world/# %Q将定义双引号字符串
2.去除所有空格:String.strip
例:" hello ".strip #=> "hello"
lstrip和rstrip分别去除字符串左右两端的空格
3.截取字符串:String[0,length]
例:new_code="hello"
code=new_code[0,new_code.length-2]#截取掉最后两位
code=> "hel"
4.数组转换成字符串
puts arr.join(",") #数组用join转换成字符串
5.字符串长度:length #字符个数
例:puts "hello".length #=>5
6.是否为空
String#empty? 方法 如果为空返回true,否则返回false
7.字符串替换
str.gsub(pattern, replacement) => new_str
str.gsub(pattern) {|match| block } => new_str
str.replace(other_str) => str
例:s = "hello" #=> "hello"
s.replace "world" #=> "world"
8.去掉重复字符:
str.squeeze([other_str]*) => new_str
"yellow moon".squeeze #=> "yelow mon" #默认去掉串中所有重复的字符
" now is the".squeeze(" ") #=> " now is the" #去掉串中重复的空格
"putters shoot balls".squeeze("m-z") #=> "puters shot balls" #去掉指定范围内的重复字符
9.字符串转换成日期:
"20120514144424".to_datetime.strftime('%Y-%m-%d %H:%M:%S')
=> "2012-05-14 14:44:24"
Ruby生成随机数和随机数和随机字符串:
rand(100000)
def newpass( len )
chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
newpass = ""
1.upto(len) { |i| newpass << chars[rand(chars.size-1)] }
return newpass
end
puts newpass(15)
转载于:https://blog.51cto.com/bohsu/1212966