代码之家  ›  专栏  ›  技术社区  ›  Jim

在Ruby中,如何根据公式(例如搜索排名)对数组进行排序?

  •  0
  • Jim  · 技术社区  · 14 年前

    所以,我正在我的第一个rails应用程序中构建快速而肮脏的搜索功能。我正在做一个查询并返回一个对象列表。例如

    @articles = Article.find_by_sql("select * from article where title like "%test%" or title like "%foobar%")
    

    下面是我试图实现的概念性伪代码。

    for each article in @articles
        calculate the article score based on how many times the search terms appear
    sort the array of articles based on the score
    

    (“分数”不是文章对象的一部分。)

    2 回复  |  直到 14 年前
        1
  •  2
  •   James    14 年前

    如果其他方法都失败了,您可以:

    @articles.sort! {|x,y| search_fitness_function(y) <=> search_fitness_function(x)}
    
        2
  •  1
  •   Jeff Swensen    14 年前

    http://dev.mysql.com/doc/refman/5.1/en/fulltext-natural-language.html

    默认或自然 函数执行自然语言 根据文本搜索字符串 收藏。集合是一组 一个或多个列包含在 作为反对()的论据给出。 对于表中的每一行,MATCH() 搜索之间的相似性度量 字符串和 在MATCH()列表中命名的列。