I want to be able to say that 2.txt contained '3' therefore the file was
not the same on that line. Thanks. MC
Then perhaps you want to feed in the lines as arrays:
require 'rubygems'
require 'diff/lcs/array'
lines1 = lines2 = nil
File.open("1.txt") { |f| lines1 = f.readlines }
File.open("2.txt") { |f| lines2 = f.readlines }
p diffs = Diff::LCS.diff(lines1, lines2)
This gives me the following output:
[[#<Diff::LCS::Change:0xb7c17fc0 @element="1,2\n", @action="-",
@position=0>, #<Diff::LCS::Change:0xb7c180d8 @element="1,2,3\n",
@action="+", @position=0>]]
That is:
- there was a single change (first element of the array)
- this change had two parts (two elements to inner array)
- remove "1,2\n" at pos 0, i.e. the first line
- add "1,2,3\n" at pos 0
It gets more interesting if you do other changes. For example, if 1.txt
contains
1,2
3,4
5,6
7,8
9,10
11,12
13,14
15,16
and 2.txt contains
1,2
3,4,5
9,9,9
5,6
7,8
9,10
11,12
13,14
15,16
17,18
Then the output becomes:(*)
[[#<Diff::LCS::Change:0xb7c19a3c @action="-", @element="3,4\n",
@position=1>,
#<Diff::LCS::Change:0xb7c199d8 @action="+", @element="3,4,5\n",
@position=1>,
#<Diff::LCS::Change:0xb7c19988 @action="+", @element="9,9,9\n",
@position=2>],
[#<Diff::LCS::Change:0xb7c19578 @action="+", @element="17,18\n",
@position=9>]]
That is: first change bundle is remove the 3,4\n at the second line (#1,
counting from zero), add 3,4,5\n, and add 9,9,9\n. The third change
bundle is to add 17,18\n at the tenth line.
HTH,
Brian.
(*) You can also change p to pp, and add 'require "pp"' to the top of
the file, to get alternative pretty-print formatting.
···
--
Posted via http://www.ruby-forum.com/\.