Mmcolli00 Mom wrote:
require ‘diff/lcs/Array’
file = File.open(“1.txt”,‘r’)
@row = {}
file.each_line do |@line|
key, val = @line.chomp.split(",",0)
@row[key] = val
end
file2 = File.open(“2.txt”,‘r’)
@row2 = {}
file2.each_line do |@line2|
key2, val2 = @line2.chomp.split(",",0)
@row2[key2] = val2
end
puts diffs = Diff::LCS.diff(@line,@line2)
You are using a very odd way of iterating, which is explicitly forbidden
in ruby 1.9. If you write
foo.each do |@bar| …
then for each element of foo, the instance variable @bar is set to that
element. So the net result here is that after the loops have finished,
@line remains set to the last line of 1.txt, and @line2 remains set to
the last line of 2.txt. You can demonstrate this by adding
p @line, @line2
just before calling Diff::LCS.
(In ruby 1.9, block parameters must be local variables, and are always
local to the block - they always drop out of scope afterwards)
So, your test program simplifies to the following:
require ‘rubygems’
require ‘diff/lcs/array’
@line = “1,2\n”
@line2 = “1,2,3\n”
puts diffs = Diff::LCS.diff(@line,@line2)
The question is, what do you expect this to do?
If you replace ‘puts’ with ‘p’ in the last line, you get the following
more detailled output:
[[#<Diff::LCS::Change:0xb7be613c @element=",", @action="+",
@position=3>, #<Diff::LCS::Change:0xb7be60d8 @element=“3”, @action="+",
@position=4>], [#<Diff::LCS::Change:0xb7be5fac @element="", @action="-",
@position=4>]]
My guess is that Diff::LCS is treating the string as a sequence of
bytes. The first change is [add “,” at pos 3, add “3” at pos 4], which
is correct. The second change is strange, as it seems to say [“remove
nothing from pos 4”]
However, since all the examples in the README show two arrays being
passed, and here you’re passing in two strings, I’m not sure this is
even a supported way of working with this library.
Your code also builds two hashes, @row and @row2, but doesn’t seem to
use them at all. Were you trying to do something with them?
Finally, your use of split may not behave the way you expect:
irb(main):002:0> key2, val2 = “1,2,3\n”.chomp.split(",",0)
=> [“1”, “2”, “3”]
irb(main):003:0> key2
=> “1”
irb(main):004:0> val2
=> “2”
That is, you’re ignoring everything after the second field.
I can strongly recommend playing around with expressions in irb, and
adding snippets of “p …expression…” within your code, to get a feel
for what’s happening.
HTH,
Brian.