Ruby输出数组中的每个元素都带有带缩进的新行



我有array = [1,2,3,4,5]

array.each do |e|
 ...
end

所以我需要像一样输出

1
 2
  3
  4
  5

我该怎么做?(如何按特定顺序输出)

假设您有一个从1到array.length的int的array,您想打印第一个缩进0到n - 1空格的n元素,然后在列中向下。

例如,对于n = 3array = [1, 2, 3, 4, 5],输出将是

1     # 0     whitespaces
 2    # 1     whitespace
  3   # n - 1 whitespaces
  4   # n - 1 whitespaces
  5   # n - 1 whitespaces

打印该序列的代码是

arr.each { |e| puts ( (e <= n ? " " * (e - 1) : " " * (n - 1)) + e.to_s ) }

假定CCD_ 8。

不妨堆积在:上

array = [1,2,3,4,5]
#array.map(&:to_s).each_with_index { |value, index| puts value.rjust(index < 3 ? index+1 : 4) }
array.each_with_index { |value, index| puts value.to_s.rjust(index < 3 ? index+1 : 4) }

最新更新