繁体   English   中英

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

[英]Ruby output array each element with new line with indent

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

array.each do |e|
 ...
end

所以我需要像这样输出

1
 2
  3
  4
  5

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

比方说,你有一个array整型从1到array.length和你想打印的第一n 0缩进元素n - 1空格,然后在列下去。

例如,当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 ) }

假设n > 0

还不如说:

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) }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM