Domanda

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?

È stato utile?

Soluzione

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

Altri suggerimenti

This isn't quite what OP was looking for, but here's a sample of sorting by modified date, to list the oldest files first. You could easily adapt this to sort by any other attributes, reverse sort, etc.

It also filters out directories and dot-files, and ultimately only returns the filename, with no preceding path.

def files_to_process
  sftp.dir
      .glob(inbox_path, '*')
      .reject { |file| file.name.starts_with?('.') }
      .select(&:file?)
      .sort { |a, b| a.attributes.mtime <=> b.attributes.mtime }
      .map(&:name)
end
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top