注册 | 登录 忘记密码? 51cto首页 | 博客 | 论坛 | 招聘
热点文章 CCIE-Lab考试将新增10分钟..
 帮助

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


2008-03-13 19:13:56
版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。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
输出结果:Fats   Waller
----

本文出自 “李骥平” 博客,请务必保留此出处http://fsjoy.blog.51cto.com/318484/65638





    文章评论
 
2008-03-14 09:35:41
不错 分享下

 

发表评论

昵   称:
验证码:  点击图片可刷新验证码  博客过2级,无需填写验证码
内   容: