简体   繁体   中英

Printing elements of array in one line in Ruby

I have got the following Ruby hash:

hash = {
0 => "
===
@@@
@ @
@ @
@ @
@@@
===",
1 => "
=
@
@
@
@
@
="}

I would like to print out some of the values of the hash in one line in the console. To that effect, I have created an array with the elements I would like printed out:

test = [hash[0], hash[1]]

or

test1 = [hash[0], hash[0]]

In case I want to print test1 to the console, the result should be the following:

======
@@@@@@
@ @@ @
@ @@ @
@ @@ @
@@@@@@
======

In case I want to print `test2 to the console, the result should be:

====
@@@@
@ @@
@ @@
@ @@
@@@@
====

However, when I use puts or print , the result is always that one is printed after another and not in the same line.

a1, a2 = hash.values.map { |s| s[1..-1].split("\n") }
  #=> [["===", "@@@", "@ @", "@ @", "@ @", "@@@", "==="],
  #    ["=", "@", "@", "@", "@", "@", "="]] 

puts a1.zip(a1).map(&:join)
======
@@@@@@
@ @@ @
@ @@ @
@ @@ @
@@@@@@
======

puts a1.zip(a2).map(&:join)
====
@@@@
@ @@
@ @@
@ @@
@@@@
====

Note:

a1.zip(a1)
  #=> [["===", "==="], ["@@@", "@@@"], ["@ @", "@ @"], ["@ @", "@ @"],
  #    ["@ @", "@ @"], ["@@@", "@@@"], ["===", "==="]]

a1.zip(a2)
  #=> [["===", "="], ["@@@", "@"], ["@ @", "@"], ["@ @", "@"],
  #    ["@ @", "@"], ["@@@", "@"], ["===", "="]] 

s[1..-1] , which drops the first character of hash[0] and hash[1] , is needed because that character is a newline ( "\\n" ). Had the two lines 0 => " and === been written 0 =>"=== (similar for hash[1] ), I could have written s.split("\\n") .

You need to create a two-dimensional structure first to be able to get the wanted result.

I suggest the following steps:

  1. Deconstruct the values in your hash

     atomic = hash.values.map{ |e| e.split("\\n")} 

    This will give you

     [["", "===", "@@@", "@ @", "@ @", "@ @", "@@@", "===" ], [ "", "=", "@", "@", "@", "@", "@", "=" ]] 
  2. Use the new data structure to build the output you need

    first case:

     test1 = atomic[0].zip(atomic[0]).map(&:join) puts test1 

    =>

     ====== @@@@@@ @ @@ @ @ @@ @ @ @@ @ @@@@@@ ====== 

    second case:

     test2 = atomic[0].zip(atomic[1]).map(&:join) 

    =>

     ==== @@@@ @ @@ @ @@ @ @@ @@@@ ==== 

I hope you find that helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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