Question

I have an array of arrays looking like this:

arr = [[0,0,0,0,0], [0,0,1,0,0], [0,1,0,1,0], [0,0,1,0,0], [0,0,0,0,0]]

and I want to make it look like this:

 00000
 00100
 01010
 00100
 00000

I tried like this:

arr.each {|a| p a.join(',').gsub(',','')}

but it outputs it like this:

 00000
 00100
 01010
 00100
 00000

whith quotes ' " " ' in the begining and the end of each row. I want it to be one single piece that starts with a quote then the rows and in the end - quote. But not quoting every single row.

Was it helpful?

Solution 2

join without an argument:

arr.each{|el| puts el.join}

OTHER TIPS

try

arr.map {|a| a.join}.join("\n")
puts arr.map(&:join)

Calling map goes through the array (the outer one) and for each entry calls the join method; it returns a new array where each entry has been replaced by the result.

The join method of an array calls to_s on each part of an array and concatenates them with an optional separator. Calling join with no arguments uses an empty string (no separator).

Calling puts on an array prints each entry on its own line.

Or, if you want the final results as a single string with embedded newlines:

str = arr.map(&:join).join("\n")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top