Skip to content

Instantly share code, notes, and snippets.

@dannysperry
Last active September 8, 2017 19:22
Show Gist options
  • Save dannysperry/e9316de8d93c66781dd2 to your computer and use it in GitHub Desktop.
Save dannysperry/e9316de8d93c66781dd2 to your computer and use it in GitHub Desktop.
String Comparing Exercise
#!/usr/bin/env ruby
require 'minitest'
require 'minitest/spec'
require 'minitest/autorun'
require 'pry-byebug'
# Hi! We have a challenge for you to complete.
#
# We've defined the differences between two strings to be the number of
# characters that don't match. For example, "bob" and "rob" are mostly the same
# except for their first letter, so their differences count would be 1.
#
# Please fill in the `differences` method below such that it passes all the
# tests. You can run this file with ruby and it should let you know if it
# passes or fails. (`ruby string_comparison.rb` in your terminal)
#
# Once you've completed this challenge, send the file back to us (email or
# however we've sent it to you is fine) and we'll take a look.
#
# Thanks and good luck!
# -Josh Szmajda
# original stand alone method used for tests.
def differences(s1, s2)
StringCombo.new(s1, s2).differences
end
# Object to hold both strings and manipulate params as attributes
class StringCombo
attr_reader :s1, :s2
def initialize(s1, s2)
@s1 = s1
@s2 = s2
end
def differences
difference_counter
end
private
def smallest_length
@s1.length <= @s2.length ? @s1.length : @s2.length
end
def difference_counter
count = 0
@s1.downcased_array.first(smallest_length).each_with_index do |char, i|
count += 1 if char != @s2.downcased_array[i]
end
count
end
end
# Reopen String class
class String
def downcased_array
downcase.split('')
end
end
# Tests
describe 'String Comparison' do
it 'returns 0 when the strings are empty' do
differences('', '').must_equal(0)
end
it 'returns 0 when the strings are identical' do
differences('Robert', 'Robert').must_equal(0)
end
it 'returns 3 for this small test' do
differences('Bob', 'Sam').must_equal(3)
end
it 'is 2 for this longer sample' do
differences('Jessica Q. Smith', 'Jessica R. Smyth').must_equal(2)
end
it 'is 1 in this case' do
differences('Samantha', 'Semantha').must_equal(1)
end
it 'ignores case matching' do
differences('Yasha Emirhan', 'Yesha EmIrhan').must_equal(1)
end
it 'ignores the extra length on the second string' do
differences('Fahri Jordan', 'Damian Tomoson').must_equal(11)
end
it 'ignores the extra length of the first string' do
differences('Randell Vilhelmas', 'Henri Nadav').must_equal(10)
end
end
@dannysperry
Copy link
Author

This file started out with an empty differences method and all the tests in their current state.

I basically got the tests passing without messing with them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment