eyoung eyoung - 4 months ago 8
Ruby Question

How to nest while loops in Ruby

I'm trying to make a simple

*
pyramid using while loops but it stops at the first five
*
. I can't figure out why.

This is my code:

x = 5
y = 0

while x > 0
while y < x
print "*"
y +=1
end

x -= 1

end

Answer

You never reset y or print a new line

x = 5
y = 0

while x > 0
    while y < x
        print "*"
        y +=1
    end 
    print "\n"
    y = 0

    x -= 1

end

Output

*****
****
***
**
*

That is bad Ruby tho

This is a much more idiomatic solution

5.downto(1) do |x|
  1.upto(x) do |y|
    print "*"
  end
  print "\n"
end

Output

*****
****
***
**
*

I don't know what the final shape of "pyramid" you're looking for, but you can likely adapt the technique above to get the desired output

Comments