gpt4 book ai didi

ruby - 如何使用 Net::SFTP 和 Ruby 检查条目是文件还是目录

转载 作者:数据小太阳 更新时间:2023-10-29 08:43:28 26 4
gpt4 key购买 nike

使用 Net::SFTPdir 我试图确定哪些条目是文件还是目录。不确定要检查什么:

Net::SFTP.start(server_ip, ftp_username, :password => ftp_password, :port => ssh_port, :timeout => 6) do |sftp|
files = sftp.dir.entries(path).select{|entry| ??? }
directories = sftp.dir.entries(path).select{|entry| ??? }
end

最佳答案

解决方案

你可以使用:

files, directories = sftp.dir.entries(path).partition{ |entry| entry.file? }

例子

p files.map(&:name)
# ["Gemfile", "Gemfile.lock", ".gitignore", "README.rdoc", "Rakefile", "sftp_pv.expect", "config.ru"]
p directories.map(&:name)
# ["data", "config", "..", "app", "tmp", "public", "vendor", "test", ".git", ".", "log", "bin", "lib", "db"]

如何找到解决方案?

我复制了您的代码,定义了连接到个人服务器所需的所有变量,并定义了到远程 Rails 项目的 path

我将你的 block 更改为 p sftp.dir.entries(path).first

结果出来了:

#<Net::SFTP::Protocol::V01::Name:0x00000000dbf3f8 @name="data", @longname="drwxr-xr-x    2 dev      dev         20480 Oct 27 10:45 data", @attributes=#<Net::SFTP::Protocol::V01::Attributes:0x00000000dbf5b0 @attributes={:size=>20480, :uid=>1002, :gid=>1003, :permissions=>16877, :atime=>1482015468, :mtime=>1477557907}>>

谷歌搜索 Net::SFTP::Protocol::V01::Name 把我带到了 documentation .

directory?file?是有前途的名字!

这个:

p sftp.dir.entries(path).first.file?

返回 false

最后,我记得在同一 block 中使用 rejectselect 可以用 partition 缩短:

Returns two arrays, the first containing the elements of enum for which the block evaluates to true, the second containing the rest.

关于ruby - 如何使用 Net::SFTP 和 Ruby 检查条目是文件还是目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41203755/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com