Simple loop question

Working on “loop”.
I can’t get the following simple loop to work. What am I doing wrong?

puts “Enter a number or ‘q’ to terminate”
loop do
n = gets.chomp
if (n == ‘q’) then
break
else
is_prime = true
for i in 2…n-1
if n % i == 0
is_prime = false
end
end
if is_prime
puts “#{n} is a prime.”
else
puts “#{n} is not a prime.”
end
end
end

Thanks in advance.

The method gets return a string, if you want to do arithmetics with it,
you need to convert it to a number first with #to_i

input=gets.chomp
n=input.to_i

Additionally, you may want to check the input for sanity – what if the
user enters “aygh” ?

Dansei Yuuki wrote in post #1179677:

The method gets return a string, if you want to do arithmetics with it,
you need to convert it to a number first with #to_i

input=gets.chomp
n=input.to_i

Additionally, you may want to check the input for sanity – what if the
user enters “aygh” ?

Thanks, Dansei. That helped. I should have thought of it. As for
character user entries, I need to tackle that now.
Thanks again!

And you don’t need all those double ranges - checking if it’s in the
middle. Just check if it’s less than the number - it will go into the
first one it meets the criteria for.% Calculate the gas fraction
vsl = 0.001;
vsl1 = vsl;
vslSave = [];
while vsl<=10
if vsl < 0.01
increment = 0.001;
elseif vsl < 0.1
increment = 0.01;
elseif vsl < 1.0
increment = 0.1;
else
increment = 1;
end

vsl = vsl + increment;
vslSave = [vslSave;vsl];
end
vslSave = [vsl1;vslSave]

In case you’re in
school/college
and more interested in getting some, more power to you buddy:

for(int i = 0; i < n; i++)
{
for(int j = 0; j <= i; j++)
System.out.print("*");
System.out.println();
}

Marc C. wrote in post #1179643:

with some refactoring :

def prime?(n)
return true if n<=3
(2…(n-1)).each {|i| return false if n % i == 0 }
true
end

loop do
print "give me a number : "
n = gets.chomp
break if n !~ /\d+/
puts prime?(n.to_i) ? “Ok, #{n} is prime” : “Sorry, #{n} is not
prime”
end
puts “bye bye”

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