用Ruby绘制星号

时间:2014-05-20 20:24:21

标签: ruby-on-rails ruby drawing

我正在尝试使用*在ruby中绘制字母X.我无法将对角线与另一条对角线相交以创建字母X.请参阅下面的代码,感谢您的帮助!

# Draw X
# Draw diagonal1
for y in 1..13
  for x in 1..(13-y)
    print " "
  end
  for x in 1..7
    print "*"
  end
  print "\n"
end

# Draw diagonal2
for y in 1..13
    for x in 1..(y-13)
            print " "
    end
    for x in 1..7
        print "*"
    end
    print "\n"
end 

1 个答案:

答案 0 :(得分:1)

在你走下一条线(print "\n")之后,你无法回头。

您应该尝试更好地计划,并同时打印两个对角线:

3.downto(0).each { |i| puts ('*' * 7 + ' ' * i*2 + '*' * 7).center(20) }
5.downto(3).each { |i| puts ('*' * (i*2+1)).center(20) }
3.upto(5).each { |i| puts ('*' * (i*2+1)).center(20) }
0.upto(3).each { |i| puts ('*' * 7 + ' ' * i*2 + '*' * 7).center(20) }