Operator and Ruby

Asked

Viewed 139 times

1

I would like that code to take two numbers and show the numbers divisible by the first, the second and the two. However I could not make the use of AND for this case, because the div_pelos2 array turns empty.

def self.divisiveis(num1, num2)
    div_num1 = Array.new
    div_num2 = Array.new
    div_pelos2 = Array.new

    for i in 1..49
        i += 1
        if i % num1 == 0
            div_num1.push (i)
        elsif i % num2 == 0
            div_num2.push (i)
        elsif (i % num1 == 0) && (i % num2 == 0) 
            div_pelos2.push (i)
        end
    end

    return div_pelos2, div_num1, div_num2
    end
end

1 answer

3


Your && is correct, the problem is in elsif. Notice this snippet:

 elsif (i % num1 == 0) && (i % num2 == 0) 

"elsif" is the same as "Else if", so this chunk of code only runs if the condition fails in the other 2 previous scenarios, which test exactly if the number is divisible by one or the other.

swap for if ... end

  • If there’s a possibility num1 and num2 are multiples of each other (which I believe there are), so the existence of any elsif will be a logical mistake. I would trade the two elsifs in accordance with that recommendation from @Orlandocorrea

Browser other questions tagged

You are not signed in. Login or sign up in order to post.