英文:
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(<file_path>, "**", "*")
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论