Compare text differences between two contents (%) using Ruby on Rails

Requirement: Compare two contents(HTML, JavaScript code or any other text) and find text difference in percentage(%) between them.

Technology: Ruby on Rails

Versions: Rails: 5.1.4 , Ruby: 2.4.1 (would work with almost any version)

Git Repo:

We are going to build something like below.

Difference Comparison (%)

For this we are going to use string metric called as Levenshtein distance.


Okay sir !!!

In information theory, Linguistics and computer science, the Levenshtein distance is a string metric for measuring the difference between two sequences. It is named after Vladimir Levenshtein, who considered this distance in 1965.

For this, we are going to use text gem. Let’s start creating our app.

$ rails new compare

This will create our rails app with name compare.

Then move to our app directory and install the dependencies.

$ bundle install

If above command gives you an error you may need install bundler gem for this.

$ gem install bundler

Now your rails app is ready. Let’s add text gem to our app. Open Gemfile and write following line to add gem.

gem 'text'

Again do bundle install to install the gem.

Let’s create controller now by the following command.

$ rails g controller comparisons compare

This will generate following files.

Output of comparison controller generation!

Add the routes at config/routes.rb

Rails.application.routes.draw do
get 'comparisons/compare'
post 'comparisons/compare_sections'
root to: 'comparisons#compare'

Now go to controllers/comparisons_controller.rb file and paste following contents.

Gist for comparisons controller

Idea below (sample code run on irb console)

irb code

So from above the distance between ankur and abkur is 20% as there is 1 character change out of 5. This is exactly what we want.

Leveraging the above functionality, the code is like below

distance = Text::Levenshtein.distance(params[:left_section], params[:right_section]).to_f

Here is the view file.


Now as we have written remote: true in the form it would send an AJAX request. Following the the AJAX response code,


Result text shows in green when both contents are same and shows in red when contents are different!

You can find the whole GitHub code here.

Ruby On Rails Developer, JavaScript Lead, Quick Learner, Reader, Writer, Always in Mood !!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store