[英]Printing elements of array in one line in Ruby
I have got the following Ruby hash: 我有以下Ruby哈希:
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: 如果我想将test1
打印到控制台,结果应如下所示:
======
@@@@@@
@ @@ @
@ @@ @
@ @@ @
@@@@@@
======
In case I want to print `test2 to the console, the result should be: 如果我想将`test2打印到控制台,结果应该是:
====
@@@@
@ @@
@ @@
@ @@
@@@@
====
However, when I use puts
or print
, the result is always that one is printed after another and not in the same line. 但是,当我使用puts
或print
,结果始终是一个接一个地打印而不是在同一行中。
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"
). 需要删除hash[0]
和hash[1]
的第一个字符的s[1..-1]
,因为该字符是换行符( "\\n"
)。 Had the two lines 0 => "
and ===
been written 0 =>"===
(similar for hash[1]
), I could have written s.split("\\n")
. 如果两行0 => "
和===
写入0 =>"===
(类似于hash[1]
),我本可以编写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: 我建议采取以下步骤:
Deconstruct the values in your hash
解构hash
值中的hash
atomic = hash.values.map{ |e| e.split("\\n")}
This will give you 这会给你
[["", "===", "@@@", "@ @", "@ @", "@ @", "@@@", "===" ], [ "", "=", "@", "@", "@", "@", "@", "=" ]]
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. 我希望你觉得有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.