How to diff two strings in Ruby

Updated . Posted . Visible to the public.

When you need to use diff in either some Ruby code or your Rails app, use the differ gem Show archive.org snapshot .

puts Differ.diff "foo", "boo"
# => {"boo" >> "foo"}

Usage

There are several variants available, all using the base method diff(to, from, separator = "\n").
You have diff_by_line, diff_by_word, diff_by_char and may of course use your own separator:

puts Differ.diff 'Hauptsatz, und mein Nebensatz.', 'Hauptsatz, und dein Nebensatz.', ','
# => Hauptsatz,{" und dein Nebensatz." >> " und mein Nebensatz."}

Formatting

Standard formatting is :ascii. You also have :html and :color formatting:

diff = Differ.diff "foo", "boo"

puts diff.format_as :html
# => <del class="differ">boo</del><ins class="differ">foo</ins>

puts diff.format_as :color
# => \e[31mboo\e[0m\e[32mfoo\e[0m
# In a terminal, this will be "boofoo" with boo being red and foo being green.

For more detailed information, check the attached link.

Dominik Schöler
Last edit
Dominik Schöler
Keywords
difference, compare
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2011-07-27 11:43)