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 ComparisonDifference Comparison (%)

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

virus elaboration

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.

Informally, the Levenshtein distance between two words is the minimum number of single-character edits (insertions, deletions or substitutions) required to change one word into the other.

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.

comparison controller generation
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 codeirb 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!

Result 1
result 2

You can find the whole github code here.

Thanks for reading. If you liked it, press the clap & share 🙂

Click here for more details…

At BoTree Technologies, we build enterprise applications with our RoR team of 25+ engineers.

We also specialize in RPA, AI, Python, Django, JavaScript and ReactJS.

Consulting is free – let us help you grow!