簡要概述Ruby字符串
今天在這里為大家介紹的內容是有關Ruby字符串的一些知識。希望初學Ruby的同學可以通過本文介紹的內容更深一步的了解這項語言的含義。#t#
1、Ruby字符串是8位字節的簡單序列,字符串是String類的對象
注意轉換機制(注意單引號與雙引號的區別),如:
單引號中兩個相連的反斜線被替換成一個反斜線,,一個反斜線后跟一個單引號被替換成一個單引號
'escape using "\\"' >> 轉義為"\" 'That\'s right' >> That's right
2、Ruby字符串雙引號支持多義的轉義
"\n"
#{expr}序列來替代任何的Ruby表達式的值 ,(全局變量、類變量或者實例變量,那么可以省略大括號)
"Seconds/day: #{24*60*60}" >> Seconds/day: 86400 "#{'Ho! '*3}Merry Christmas" >> Ho! Ho! Ho! Merry Christmas "This is line #$." >> This is line 3
3、here document來創建一個字符串,end_of_string 為結束符號
aString = <<END_OF_STRING The body of the string is the input lines up to one ending with the same text that followed the '<<' END_OF_STRING
4、%q和%Q分別把Ruby字符串分隔成單引號和雙引號字符串(即%q與%Q后面的符號具有',"的功能)
%q/general single-quoted string/ >> general single-quoted string
5、String 常用功能
String#split:把行分解成字段
String#chomp:去掉換行符
String#squeeze:剪除被重復輸入的字符
String#scan:以指定想讓塊匹配的模式
/jazz/j00132.mp3 | 3:45 | Fats Waller | Ain't Misbehavin'
/jazz/j00319.mp3 | 2:58 | Louis Armstrong | Wonderful World
6、文件格式如上,要進行分解
songs = SongList.new
songFile.each do |line|
file, length, name, title = line.chomp.split(/\s*\|\s*/)#先chomp,后再分解,/\s*表示任字符
name.squeeze!(" ")#替換空格
mins, secs = length.scan(/\d+/)#這里用scan匹配模式
songs.append Song.new(title, name, mins.to_i*60+secs.to_i)