Compare Text Differences Between Two Contents (%) Using Ruby on Rails
Technology: Ruby on Rails
Versions: Rails: 5.1.4 , Ruby: 2.4.1 (would work with almost any version)
Git Repo: https://github.com/AnkurVyas-BTC/compare
We are going to build something like below.
Difference Comparison (%)
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.
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
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)
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.
Thanks for reading. If you liked it, press the clap & share 🙂
At BoTree Technologies, we build enterprise applications with our RoR team of 25+ engineers.
Consulting is free – let us help you grow!
Choose Your Language
- Digital Marketing
- IT Consulting
- Project Management
- Salesforce Development