0

I have:

def distance(str1, str2)
  str1.chars.each_index do |index| 
    difference?(str1, str2, index)
  end
end

def difference?(str1, str2, index)
  if !str1.chars[index].nil? && !str2.chars[index].nil?
    str1.chars[index] != str2.chars[index]
  end
end

For each element in str1.chars, which are different from elements in str2.chars with the same index, difference? returns true.

How can I count how many times it returned true in distance?

I used something like this:

def distance(str1, str2)
  distance = 0
  str1.chars.each_index do |index| 
    if  difference?(str1, str2, index)
      distance += 1
    end
  end
  distance
end

Is there a better way to do this? Maybe count with a block is the answer, but I can't figure it out.

2 Answers 2

1
def distance(str1, str2)
  str1.each_char.with_index.count do |_, index| 
    difference?(str1, str2, index)
  end
end

distance("foo", "bar") # => 3
distance("foo", "foobar") # => 0
distance("foobar", "foo") # => 0
Sign up to request clarification or add additional context in comments.

1 Comment

I like this solution, but can you explain why there is _ inside |_, index|?
0

This is known as the Levenshtein Distance. There's a gem for that:

require 'levenshtein'
Levenshtein.distance("abc","abd") #=> 1

The gem is likely to be faster than other solutions because it uses native extensions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.