diff a ruby string or array

Solution 1:

For arrays, use the minus operator. For example:

>> foo = [1, 2, 3]
=> [1, 2, 3]
>> goo = [2, 3, 4]
=> [2, 3, 4]
>> foo - goo
=> [1]

Here the last line removes everything from foo that is also in goo, leaving just the element 1. I don't know how to do this for two strings, but until somebody who knows posts about it, you could just convert each string to an array, use the minus operator, and then convert the result back.

Solution 2:

I got frustrated with the lack of a good library for this in ruby, so I wrote http://github.com/samg/diffy. It uses diff under the covers, and focuses on being convenient, and providing pretty output options.

Solution 3:

diff.rb is what you want, which is available at http://users.cybercity.dk/~dsl8950/ruby/diff.html via internet archive:

http://web.archive.org/web/20140421214841/http://users.cybercity.dk:80/~dsl8950/ruby/diff.html

Solution 4:

For strings, I would first try out the Ruby Gem that @sam-saffron mentioned below. It's easier to install: http://github.com/pvande/differ/tree/master

gem install differ

irb
require 'differ'

one = "one two three"
two = "one two 3"

Differ.format = :color
puts Differ.diff_by_word(one, two).to_s

Differ.format = :html
puts Differ.diff_by_word(one, two).to_s