narspeth
narspeth

Reputation: 3

How do I count true values returned by array iteration with condition?

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.

Upvotes: 0

Views: 129

Answers (2)

Mark Thomas
Mark Thomas

Reputation: 37517

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.

Upvotes: 0

sawa
sawa

Reputation: 168169

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

Upvotes: 1

Related Questions