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
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
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.