开发者

Ruby: how does one print a 2D array?

puts WINNING_ROWS.each{ |solution| "[ #{solution.map{ 开发者_开发知识库|space| "#{space}"}} ]"}

I tried doing the above, but it just lists each value with a new line char afterwards.

I'm trying to get the output:

[stuff,in,row,1]
[stuff,in,row,2]
etc


If this is just for debugging, the usual way is to say either

p expression

or

puts expression.inspect

...which is about the same thing.

You can also use pp.

require 'pp'
pp expression

pp(expr)


One could do something like this:

WINNING_ROWS = [[1,2,3],[4,5,6]]
WINNING_ROWS.map { |x| x.inspect }.join("")

Which will get you a string formatted as you requested


You're relying on the default to_s of Array. #each returns the array itself. So what you're doing is the same as puts WINNING_ROWS. Also, keep in mind that puts adds a newline at the end, so if you don't want that you have to use write (which is not available in the Kernel module like puts is, so you must call it directly on your STDOUT output).

You probably want something like:

WINNING_ROWS = [[1,2,3],[4,5,6]]
WINNING_ROWS.each {|row| STDOUT.write row.inspect }

=> [1, 2, 3][4, 5, 6]

# or this may work for you as well
# STDOUT.write WINNING_ROWS.inspect
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜