ruby 操作字符串 实现关键字搜索功能
版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://fsjoy.blog.51cto.com/318484/65638 |
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---- 本文出自 “李骥平” 博客,请务必保留此出处http://fsjoy.blog.51cto.com/318484/65638 本文出自 51CTO.COM技术博客 |


class Song
fsjoy1983
博客统计信息
热门文章
最新评论
友情链接
