簡要概述Ruby字符串
今天在這里為大家介紹的內(nèi)容是有關(guān)Ruby字符串的一些知識(shí)。希望初學(xué)Ruby的同學(xué)可以通過本文介紹的內(nèi)容更深一步的了解這項(xiàng)語言的含義。#t#
1、Ruby字符串是8位字節(jié)的簡單序列,字符串是String類的對(duì)象
注意轉(zhuǎn)換機(jī)制(注意單引號(hào)與雙引號(hào)的區(qū)別),如:
單引號(hào)中兩個(gè)相連的反斜線被替換成一個(gè)反斜線,,一個(gè)反斜線后跟一個(gè)單引號(hào)被替換成一個(gè)單引號(hào)
'escape using "\\"' >> 轉(zhuǎn)義為"\" 'That\'s right' >> That's right
2、Ruby字符串雙引號(hào)支持多義的轉(zhuǎn)義
"\n"
#{expr}序列來替代任何的Ruby表達(dá)式的值 ,(全局變量、類變量或者實(shí)例變量,那么可以省略大括號(hào))
"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來創(chuàng)建一個(gè)字符串,end_of_string 為結(jié)束符號(hào)
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字符串分隔成單引號(hào)和雙引號(hào)字符串(即%q與%Q后面的符號(hào)具有',"的功能)
%q/general single-quoted string/ >> general single-quoted string
5、String 常用功能
String#split:把行分解成字段
String#chomp:去掉換行符
String#squeeze:剪除被重復(fù)輸入的字符
String#scan:以指定想讓塊匹配的模式
/jazz/j00132.mp3 | 3:45 | Fats Waller | Ain't Misbehavin'
/jazz/j00319.mp3 | 2:58 | Louis Armstrong | Wonderful World
6、文件格式如上,要進(jìn)行分解
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)