[Note: parts of this message were removed to make it a legal post.]
On Wed, Mar 9, 2011 at 11:27 PM, JP Billaud <> wrote:
> class String
> def compare_sum_errors other
> cnt = [self.length, other.length].min
>
> (0..(cnt-1)).inject(0) do |errors, idx|
> next errors + 1 if self[idx] != other[idx]
> errors
> end + (self.length - other.length).abs
> end
> end
>
> str1 = "test origin string"
> str2 = "test diff string"
>
> puts str1.compare_sum_errors str2
>
This isn't the best use of inject.
This is much more readable, I find:
def count_errors(first, second)
# reorder things so that first is always <= second
first, second = [first, second].sort_by { |s| s.length }
errors = 0
first.chars.zip(second.chars).each do |f, s|
errors += 1 if f != s
end
# over-typing is an error
errors + (second.length - first.length)
end
count_errors("hello", "helloo") #=> 0
count_errors("hello", "helllo") #=> 2
str1 = "test origin string"
str2 = "test diff string"
count_errors(str1, str2) #=> 13 (same result as the inject)