如何在Ruby中制作以下模式?

Ayu*_*ush 0 ruby

A

B B

C C C

D D D D

E E E E E

我不知道如何打印字母

ray*_*ray 5

您可以执行以下操作来解决:

('A'..'F').each.with_index(1) { |letter,index| puts "#{letter} "*index }
Run Code Online (Sandbox Code Playgroud)

替代方法包括使range可变:

lower_limit = 'A'   # could be read in rather than wired
upper_limit = 'F'   # ditto
(lower_limit..upper_limit).each.with_index(1) { |letter,index| puts "#{letter} "*index }
Run Code Online (Sandbox Code Playgroud)

或使用带有的数组join获取空格而不引入尾随空格:

(lower_limit..upper_limit).each.with_index(1) { |letter,index| puts Array.new(index) { letter }.join(' ') }
Run Code Online (Sandbox Code Playgroud)

  • 您不需要数组,只需使用范围`('A'..'Z')`。还可以使用each.with_index(1)来避免每次迭代都必须执行i + 1。 (2认同)