class Song

def initialize(format, name, title, duration)

@format=format

@name=name

@title=title

@duration=duration

end

attr_accessor :format, :name, :title, :duration

end
class WordIndex
def initialize
@index={}
end
def add_to_index(obj, *phrases)
phrases.each do|phrase|
phrase.scan(/\w[-\w'']+/) do |word|
word.downcase!
@index[word]=[] if @index[word].nil?
@index[word].push(obj)
end
end
end
def lookup(word)
@index[word.downcase]
end
end
class SongList

def initialize

@songs=Array.
new
@index=WordIndex.
new

end

def append(song)

@songs.push(song)
@index.add_to_index(song, song.title, song.name)

self

end

def [](index)

@songs[index]

end

def length

@songs.length

end
def lookup(word)
@index.lookup(word)
end

end
f=File.open('test')

songs=SongList.
new

f.each
do |line|

format, duration, name, title= line.split(/\s*\|\s*/)

song=Song.
new(format, name, title, duration)

songs.append(song)

end
(0..songs.length-1).each
do |n|

puts
"#{songs[n].format}--#{songs[n].name}--#{songs[n].duration}--#{songs[n].title}"

end

puts songs.lookup('fats')

puts songs[0].name
输出结果:Fats Waller
----
本文转自 fsjoy1983 51CTO博客,原文链接:http://blog.51cto.com/fsjoy/65638,如需转载请自行联系原作者