Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the difference between strings in Ruby

Tags:

string

ruby

I need to take two strings, compare them, and print the difference between them.

So say I have:

teamOne = "Billy, Frankie, Stevie, John"
teamTwo = "Billy, Frankie, Stevie"

$ teamOne.eql? teamTwo 
=> false

I want to say "If the two strings are not equal, print whatever it is that is different between them. In this case, I'm just looking to print "John."

like image 559
btw Avatar asked Jan 08 '09 21:01

btw


People also ask

How do you compare strings in Ruby?

In Ruby, we can use the double equality sign == to check if two strings are equal or not. If they both have the same length and content, a boolean value True is returned. Otherwise, a Boolean value False is returned.

How are symbols different from strings in Ruby?

What is the difference between a symbol and a string? A string, in Ruby, is a mutable series of characters or bytes. Symbols, on the other hand, are immutable values. Just like the integer 2 is a value.

How do you find the part of a string in Ruby?

Accessing Characters Within a String To print or work with some of the characters in a string, use the slice method to get the part you'd like. Like arrays, where each element corresponds to an index number, each of a string's characters also correspond to an index number, starting with the index number 0.


1 Answers

All of the solutions so far ignore the fact that the second array can also have elements that the first array doesn't have. Chuck has pointed out a fix (see comments on other posts), but there is a more elegant solution if you work with sets:

require 'set'

teamOne = "Billy, Frankie, Stevie, John"
teamTwo = "Billy, Frankie, Stevie, Zach"

teamOneSet = teamOne.split(', ').to_set
teamTwoSet = teamTwo.split(', ').to_set

teamOneSet ^ teamTwoSet # => #<Set: {"John", "Zach"}>

This set can then be converted back to an array if need be.

like image 155
Zach Langley Avatar answered Sep 26 '22 18:09

Zach Langley