Search code examples
rubysortingnet-sftp

Net::SFTP sort directory files?


I'm currently doing the following to get a list of all the files in a directory:

Net::SFTP.start('host', 'username', :password => 'password') do |sftp|
  sftp.dir.foreach("/path") do |entry|
    puts entry.name
  end
end

But that lists the files seemingly at random. I need to order the files by name.

So, how can I sort the files by name?


Solution

  • Since SFTP is just returning the sorting that was sent by your server, you could manually sort the results:

    entries = sftp.dir.entries("/path").sort_by(&:name)
    entries.each do |entry|
      puts entry.name
    end