defwords_from_string(string)string.downcase.scan(/[\w']+/)endpwords_from_string("But I didn't inhale, he said (emphatically)")produces:
["but","i","didn't","inhale","he","said","emphatically"]
string=<<END_OF_STRING
The body of the string is the input lines up to
one starting with the same text that followed the '<<'
END_OF_STRINGNormally,thisterminatormuststartincolumnone.However,ifyouputaminussignafterthe<<characters,youcanindenttheterminator:
string=<<-END_OF_STRING
The body of the string is the input lines up to
one starting with the same text that followed the '<<'
END_OF_STRING
String#split 方法
依据分隔符(可以是,正则表达式),对字符串进行分解,提前可用字段。
例子,提取歌曲信息:
1
2
3
4
tut_stdtypes/songdata
/jazz/j00132.mp3 | 3:45 | Fats Waller | Ain't Misbehavin'
/jazz/j00319.mp3 | 2:58 | Louis Armstrong | Wonderful World
/bgrass/bg0732.mp3| 4:09 | Strength in Numbers | Texas Red
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Song=Struct.new(:title,:name,:length)File.open("songdata")do|song_file|songs=[]song_file.eachdo|line|file,length,name,title=line.chomp.split(/\s*\|\s*/)name.squeeze!(" ")mins,secs=length.scan(/\d+/)songs<<Song.new(title,name,mins.to_i*60+secs.to_i)endputssongs[1]endproduces:
#<struct Song title="Wonderful World", name="Louis Armstrong", length=178>
字符串中搜索 include?
1
2
3
4
my_string="abcdefg"ifmy_string.include?"cde"puts"String includes 'cde'"end
数组
定义、初始化、引用
如下例:
1
2
3
4
5
6
7
8
9
a=[1,'cat',3.14]# array with three elementsputs"The first element is #{a[0]}"# set the third elementa[2]=nilputs"The array is now #{a.inspect}"# inspect 将 Array 转换为字符串格式:[ 元素1,元素2, ... ]produces:
Thefirstelementis1Thearrayisnow[1,"cat",nil]
Ranges as Sequences
In Ruby, these sequences are created using the .. and … range operators. The two-dot form creates an
inclusive range, and the three-dot form creates a range that excludes the specified high value.
car_age=gets.to_f# let's assume it's 9.5casecar_agewhen0...1puts"Mmm.. new car smell"when1...3puts"Nice and new"when3...10puts"Reliable but slightly dinged"when10...30puts"Clunker"elseputs"Vintage gem"end
line=gets# replace first 'Perl' with 'Ruby'newline=line.sub(/Perl/,'Ruby')# replace every 'Python' with 'Ruby'newerline=newline.gsub(/Python/,'Ruby')# You can replace every occurrence of Perl and Python with Ruby using this:newline=line.gsub(/Perl|Python/,'Ruby')