mockra

Array Diff - 20 Jun 2013


For one of my side projects, I wanted to find the differences between two arrays. I needed to know what additions/deletions to make on one array to recreate the other.

Here’s the solution I came up with:

class ArrayDiff
attr_reader :one, :two
def initialize one, two
@one, @two = one.to_a, two.to_a
end
def deletions
one_dup = one.clone
two.each { |x| one_dup.slice!(one_dup.index(x)) if one_dup.index(x) }
one_dup
end
def additions
two_dup = two.clone
one.each { |x| two_dup.slice!(two_dup.index(x)) if two_dup.index(x) }
two_dup
end
end
describe ArrayDiff do
let(:array_diff) { ArrayDiff.new [1, 2, 2, 3, 6, 6, 7, 7, 7],
[2, 3, 3, 4, 8, 9] }
describe '#deletions' do
it 'returns array of deletions' do
expect(array_diff.deletions).to eq [1, 2, 6, 6, 7, 7, 7]
end
end
describe '#additions' do
it 'returns array of additions' do
expect(array_diff.additions).to eq [3, 4, 8, 9]
end
end
end
view raw array_diff.rb hosted with ❤ by GitHub