change it to one-liner : `def compute(dn1, dn2) raise argumenterror if dn1.length != dn2.length count = 0 dn1.length.times do |i| count += 1 if dn1[i] != dn2[i] end count end end` in ruby

Here's how you can change the code to a one-liner in Ruby:

main.rb
def compute(dn1, dn2)
  raise ArgumentError, "Lengths of dn1 and dn2 do not match" unless dn1.length == dn2.length
  dn1.chars.zip(dn2.chars).count { |a, b| a != b }
end
170 chars
5 lines

Explanation:

  1. We use the zip method to combine each character of dn1 with the corresponding character of dn2. This creates an array of pairs.
  2. Then, we use the count method with a block that checks if the characters in each pair are not equal. The count method counts the number of elements that satisfy the block condition.
  3. The result is the count of characters that are not equal in the same index positions of dn1 and dn2.

Note: I have also added a raise ArgumentError to handle the case where the lengths of dn1 and dn2 do not match.

related categories

gistlibby LogSnag