如何用Ruby循环生成任意符号正方形?代码问题排查与修正
Fixing Your Ruby Square Generator Code
Let's break down why your code isn't working, then tweak it step by step to get that square you want!
What's Wrong With the Current Code?
Let's go through the issues one by one:
- You're not printing the result: When you run
symbol*number, Ruby creates the string of repeated symbols, but you never tell it to display that string on the screen. You need to useputsorprintto output the generated line. - Your loop only runs once: The
loop doblock has abreakstatement right after the string calculation, so it exits immediately—there's no chance to repeat the line multiple times to form a square.
How to Fix It
The simplest way to generate a square is to repeat the line of symbols exactly number times. Ruby's Integer#times method is made for this kind of repeated task. Here's the revised code:
puts "Please insert a symbol (eg. #, @, $, %, ^, &, *, _, -, +, =)" symbol = gets.chomp puts "Please insert a number" number = gets.chomp.to_i # Generate each line of the square number.times do puts symbol * number end
Let's Test It
If you input 4 for the number and & for the symbol, you'll get this output:
&&&& &&&& &&&& &&&&
Alternative: Using a Loop With a Counter
If you want to stick with a loop instead of times, you can add a counter variable to track how many lines you've printed:
puts "Please insert a symbol (eg. #, @, $, %, ^, &, *, _, -, +, =)" symbol = gets.chomp puts "Please insert a number" number = gets.chomp.to_i counter = 0 loop do puts symbol * number counter += 1 break if counter == number end
This works too—we increment the counter each time the loop runs, and stop once we've printed exactly number lines.
内容的提问来源于stack exchange,提问作者Avery
相关产品推荐
相关产品推荐

