Read more

How to diff two strings in Ruby

Dominik Schöler
July 27, 2011Software engineer at makandra GmbH

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

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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.

Posted by Dominik Schöler to makandra dev (2011-07-27 13:43)