如何在Ruby中打印一个数组?

huangapple go评论55阅读模式
英文:

How to print an array in Ruby?

问题

我正在编写一个程序来读取嵌套目录和文件的目录,并返回一个匹配文件/目录结构的嵌套数组。

我有以下内容:

dirs = File.join(<file_path>, "**", "*")
dirs_array = Dir.glob(dirs)

当我打印 dirs_array 时,我得到了所有文件路径的列表,但它不是数组格式。然而,当我调用 'dirs_array.class' 时,输出是 Array。我在这里漏掉了什么?我如何使 dirs_array 以数组格式打印?

英文:

I am writing a program to read a directory of nested directories and files and get back a nested array that matches the file/directory structure.

I have the following:

dirs = File.join(&lt;file_path&gt;, &quot;**&quot;, &quot;*&quot;)
dirs_array = Dir.glob(dirs)

When I prints dirs_array, I get back a list of all the file paths but it's not in array format. However, when I call 'dirs_array.class' the output is Array. What am I missing here? And how do I get the dirs_array to print in array format?

答案1

得分: 1

你可能得到了一个数组,但你没有看到它,因为 puts 试图处理它,而是逐行打印一个条目。这可能会掩盖内部结构。

要显示结构:

puts dirs_array.inspect

还有一个简化的形式:

p dirs_array

或者,如果你喜欢花哨一点,你可以使用“漂亮的打印器”:

pp dirs_array

这种形式更冗长,但可以帮助揭示更复杂的结构。

英文:

You're likely getting an Array back, but you're not seeing it because puts tries to work with that and instead prints one entry per line. This can obscure the internals.

To show the structure:

puts dirs_array.inspect

There's also a shorthand form for this:

p dirs_array

Or if you like things fancy you can use the "pretty printer":

pp dirs_array

This form is more verbose, but can help reveal more complex structures.

huangapple
  • 本文由 发表于 2023年6月5日 22:12:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76407309.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定