Mandamus Mandamus - 1 year ago 86
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)

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

This gives an error, how can I fix it?

The output from cmd prompt:

Answer Source

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"
  puts "#{num} is not prime"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download