Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Simple recommendation system written in Ruby based on Jaccard index.
# Simple Recommendation Engine in Ruby
# Visit:
# Author: Oto Brglez <>
class Book <
def words
@words ||= self.title.gsub(/[a-zA-Z]{3,}/).map(&:downcase).uniq.sort
class BookRecommender
def initialize book, books
@book, @books = book, books
def recommendations! do |this_book|
this_book.define_singleton_method(:jaccard_index) do @jaccard_index; end
this_book.define_singleton_method("jaccard_index=") do |index|
@jaccard_index = index || 0.0
intersection = (@book.words & this_book.words).size
union = (@book.words | this_book.words).size
this_book.jaccard_index = (intersection.to_f / union.to_f) rescue 0.0
end.sort_by { |book| 1 - book.jaccard_index }
# Usage
# Load books from this file
BOOKS ="\n").map { |l| }
# Create initial book
this_book ="Ruby programming language")
# Load recommender
recommender =, BOOKS)
# Find recommendations
recommended_books = recommender.recommendations
# Show books that match the most
recommended_books.each do |book|
puts "#{book.title} (#{'%.2f' % book.jaccard_index})"
Finding the best language for the job
Could Ruby save the day
Python will rock your world
Is Ruby better than Python
Programming in Ruby is fun
Python to the moon
Programming languages of the future

This comment has been minimized.

Copy link

@reddyonrails reddyonrails commented Mar 24, 2014

K - means is also another option

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment