Calculating the difference between text strings in Ruby
17/12/07 00:40 Filed in: Ruby
The wonderful diff tool in Unix allows us to compare two or more text files for changes. This article will show you how to achieve the same effect and explain how to calculate the difference between text strings programmatically in Ruby
Since we don't want to reinvent the wheel but rather show you how to spin the wheel the first thing to do is to download Algorithm:Diff and unpack it in your project directory.
In Ruby you can then load this module with
To calculate the difference between two strings:
You can patch the original string with these differences:
Tip for FreeBSD users: the diff module is available in the ports collection:
Since we don't want to reinvent the wheel but rather show you how to spin the wheel the first thing to do is to download Algorithm:Diff and unpack it in your project directory.
In Ruby you can then load this module with
require "algorithm/diff"
To calculate the difference between two strings:
diffs = "Hello world!".diff("hello world!")You can patch the original string with these differences:
"Hello world!".patch(diffs)
=> "hello world!"
Tip for FreeBSD users: the diff module is available in the ports collection:
$ cd /usr/ports/textproc/ruby-diff
$ make install clean
|