Why does this fail

<html

xmlns=“http://www.w3.org/1999/xhtml”>

Hello,

I have made this class


def Hamming.compute(string1,string2)
    count = 0
    for s in 0.. ((string1.length)-1)  

      if string1[s] != string2[s]

         if string2[s] != nil

              count +=1
        end

    end
    return count
end


then it works fine.

But when I change it to :

def Hamming.compute(string1,string2)
   count = 0
    for s in 0.. ((string1.length)-1)
        count +=1 if string1[s] != string2[s] || string2[s] != nil
     end
   return count
end

then it gives the wrong answers.

Can anyone explain to me why this happens.

Roelof

Firstly, you dont need string2[s] != nil because if there is something
at string2[s] it will evaluate to true anyhow.

The problem is you used ||, which is logical or but you meant to use
logical and &&. In your code if statement evaluates to true whenever
string2[s] is true OR string1[s] != string2[s] is true.

Also you probably want to use string2[s] as the first condition so that
if it is false the other condition will not be executed. Heres how I
would write your code

def Hamming.compute(string1,string2)
count = 0
for s in 0(string1.length)
count += 1 if string2[s] && string1[s] != string2[s]
end

return count
end

Mistral

Change II (or) to && (and).

From a quick glance

if string1[s] != string2[s]
if string2[s] != nil
count +=1
end
end

and

count +=1 if string1[s] != string2[s] || string2[s] != nil

Are not equivalent. The nested if statements are an implied && but your
rewrite is is using ||

count +=1 if string1[s] != string2[s] && string2[s] != nil

Should fix things

There’s lots of ways to do that.

One more “readable” (to me, of course :wink: ) is to use iterators.

def Hamming.compute(string1, string2)
count = 0

iterator1 = string1.each_char
iterator2 = string2.each_char

loop do
count +=1 if iterator1.next != iterator2.next
end

count
end

When one of the iterators reaches its end it raises a StopIteration
exception and the loop statement just exits from the loop.

Abinoam Jr.

On Mon, May 26, 2014 at 11:23 AM, Peter H.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs