Mandamus Mandamus - 4 months ago 11
Ruby Question

Ruby looping program gives error

Here's what I wrote to check if a number is prime or not

print "Enter number : "
num = gets.chomp
i = 1
boo = true
while (i<num)
if (i%num==0)
boo=true
end
i++
end

if (boo==true)
puts (num+"is a prime number")
else
puts (num+"is not a prime number")
end


This gives an error, how can I fix it?

The output from cmd prompt:


Answer

Some problems:

  • ++ operator doesn't exist in Ruby, you can use += 1 instead
  • your num is a string, you can make it a number with to_i method, like num.to_i
  • if the reminder of your number divided by a precedent number is zero you should set to false, not true
  • if you start at 1 your number will result always prime

Anyway, in a more idiomatic Ruby you can write this code something like

print "Enter number : "
num = gets.chomp.to_i
prime = (2..num - 1).all? { |i| num % i != 0 }
if prime
  puts "#{num} is prime"
else
  puts "#{num} is not prime"
end