给定以下数组,如何在多行上打印出来

时间:2021-03-24 07:36:01
array = [[1, 2, 3], [8, 9, 4], [7, 6, 5]]

I keep getting it in a single line, how can I print it out in the terminal so each array is on its own individual line like so:

我一直把它放在一行,如何在终端中打印出来,这样每个阵列都在各自的行上,如下所示:

[[1, 2, 3], 
 [8, 9, 4], 
 [7, 6, 5]]

4 个解决方案

#1


2  

Try printing the mapped result of #inspect on array, like so:

尝试在数组上打印#inspect的映射结果,如下所示:

puts array.map(&:inspect)

# [1, 2, 3]
# [8, 9, 4]
# [7, 6, 5]

Hope this helps!

希望这可以帮助!

#2


2  

The following should work:

以下应该有效:

   array.each do |sub|
     puts sub.join(", ")
   end

However, this will not include the [] characters, but will look like this:

但是,这不包括[]字符,但是看起来像这样:

1, 2, 3
8, 9, 4
7, 6, 5

#3


2  

array = [[1, 2, 3], [8, 9, 4], [7, 6, 5]]
puts array.to_s.gsub('],',"],\n")

#[[1, 2, 3],
# [8, 9, 4],
# [7, 6, 5]]

#4


2  

Just for fun - you can redefine inspect method like:

只是为了好玩 - 您可以重新定义检查方法,如:

def array.inspect
  map(&:to_s).join("\n")
end
p array
# [1, 2, 3]
# [8, 9, 4]
# [7, 6, 5]

#1


2  

Try printing the mapped result of #inspect on array, like so:

尝试在数组上打印#inspect的映射结果,如下所示:

puts array.map(&:inspect)

# [1, 2, 3]
# [8, 9, 4]
# [7, 6, 5]

Hope this helps!

希望这可以帮助!

#2


2  

The following should work:

以下应该有效:

   array.each do |sub|
     puts sub.join(", ")
   end

However, this will not include the [] characters, but will look like this:

但是,这不包括[]字符,但是看起来像这样:

1, 2, 3
8, 9, 4
7, 6, 5

#3


2  

array = [[1, 2, 3], [8, 9, 4], [7, 6, 5]]
puts array.to_s.gsub('],',"],\n")

#[[1, 2, 3],
# [8, 9, 4],
# [7, 6, 5]]

#4


2  

Just for fun - you can redefine inspect method like:

只是为了好玩 - 您可以重新定义检查方法,如:

def array.inspect
  map(&:to_s).join("\n")
end
p array
# [1, 2, 3]
# [8, 9, 4]
# [7, 6, 5]