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."
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With