ruby 操作字符串 实现关键字搜索功能

InBlock.gif class Song
InBlock.gif  def initialize(format, name, title, duration)
InBlock.gif    @format=format
InBlock.gif    @name=name
InBlock.gif    @title=title
InBlock.gif    @duration=duration
InBlock.gif  end
InBlock.gif  
InBlock.gif  attr_accessor :format, :name, :title, :duration
InBlock.gif  
InBlock.gifend
InBlock.gif
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
InBlock.gif
class SongList
InBlock.gif  def initialize
InBlock.gif    @songs=Array. new
InBlock.gif     @index=WordIndex. new
InBlock.gif  end
InBlock.gif  
InBlock.gif  def append(song)
InBlock.gif    @songs.push(song)
InBlock.gif     @index.add_to_index(song, song.title, song.name)
InBlock.gif    self
InBlock.gif  end
InBlock.gif  
InBlock.gif  def [](index)
InBlock.gif    @songs[index]
InBlock.gif  end
InBlock.gif  
InBlock.gif  def length
InBlock.gif    @songs.length
InBlock.gif  end
InBlock.gif  
InBlock.gif   def lookup(word)
InBlock.gif     @index.lookup(word)
InBlock.gif   end
InBlock.gifend
InBlock.gif
f=File.open('test')
InBlock.gifsongs=SongList. new
InBlock.giff.each  do |line|
InBlock.gif  format, duration, name, title= line.split(/\s*\|\s*/)
InBlock.gif  song=Song. new(format, name, title, duration)
InBlock.gif  songs.append(song)
InBlock.gifend
InBlock.gif
(0..songs.length-1).each  do  |n|
InBlock.gif puts   "#{songs[n].format}--#{songs[n].name}--#{songs[n].duration}--#{songs[n].title}"
InBlock.gifend
InBlock.gifputs songs.lookup('fats')
InBlock.gifputs songs[0].name
输出结果:Fats   Waller
----




本文转自 fsjoy1983 51CTO博客,原文链接:http://blog.51cto.com/fsjoy/65638,如需转载请自行联系原作者
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值