Search code examples
crystal-lang

How do I list files and directories those are not hidden in current directory using crystal language?


I wrote my own minimal version of "ls" command (Linux) using crystal language and here is my code:

require "dir"
require "file"

def main()

    pwd = Dir.current
    list_dir = Dir.children(pwd)
    
    puts("[+] location: #{pwd}")
    puts("------------------------------------------")
    
    list_dir.each do |line|

        check = File.file?(line)

        if check == true
            puts("[+] file     : #{line}")
        elsif check == false
            puts("[+] directory: #{line}")
        else 
            puts("[+] unknown  : #{line}")
        end
    end
end

main

It works but it also listing all hidden files and directories (.files & .directories) too and I do not want to show those. I want the result more like "ls -l" command's result not like "ls -la". So, what I need to implement to stop showing hidden files and directories?


Solution

  • There is nothing special about "hidden" files. It's just a convention to hide file names starting with a dot in some contexts by default. Dir.children does not follow that convention and expects the user to apply approriate filtering.

    The recommended way to check if a file name starts with a dot is file_name.starts_with?(".").