Reputation: 3
I'm trying to get the numbers in numbers
to print out.
But when the if-expression
comes before the numbers are appended, it doesn't seem to print. Only if I put the if-expression
after, it will. Why is this?
numbers = []
while numbers.size < 5
if numbers.size == 5
puts numbers
break
end
numbers << rand(0..99)
end
Upvotes: 0
Views: 304
Reputation: 3366
Your code doesn't work because the while loop exits before the if condition is true.
What's more, the if
block is unnecessary and makes your code confusing and inefficient.
Lemme refactor it for ya...
Generates an array of 5 random integers between 0 and 99 and then prints it
numbers = []
while numbers.size < 5
numbers << rand(0..99)
end
puts numbers
Upvotes: 0
Reputation: 1434
This happens because you have numbers.size < 5
.
As soon as numbers.size
is 5
, the while
is no longer true. You can use <=
(or numbers.size < 6
) if you want it to ONLY print when it is exactly 5.
numbers = []
while numbers.size <= 5
if numbers.size == 5
puts numbers
break
end
numbers << rand(0..99)
end
Or you could write this in a more ruby style:
numbers = []
5.times do numbers << rand(0..99) end
puts numbers
Upvotes: 1
Reputation: 49
1.Case 1: If statement placed before appending
The reason is because the loop will not execute when numbers.size == 5 because the condition you've set is while numbers.size < 5.
2. If statement is placed after appending
Placing the if statement after appending the numbers list will work because you're still within the body of the loop i.e. you're still executing the loop for which the condition you set was true.
Upvotes: 0