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.
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
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.
Add the routes at
root to: 'comparisons#compare'
Now go to
controllers/comparisons_controller.rb file and paste following contents.
Idea below (sample code run on irb console)
So from above the distance between
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 :)