You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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 use puts or print to output the generated line.
  • Your loop only runs once: The loop do block has a break statement 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:03:00