문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top