加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby File ::目录?问题

发布时间:2020-12-16 20:32:17 所属栏目:百科 来源:网络整理
导读:我是红宝石的新手,但是非常喜欢它.有些事情给了我一些麻烦,下面也不例外. 我想在这里做的是通过分类“Dir”创建一种“超级目录”.我添加了一个名为“subdirs”的方法,该方法旨在列出目录对象的文件,并将其推送到数组中,如果文件是目录本身.问题是,我的测试(F
我是红宝石的新手,但是非常喜欢它.有些事情给了我一些麻烦,下面也不例外.

我想在这里做的是通过分类“Dir”创建一种“超级目录”.我添加了一个名为“subdirs”的方法,该方法旨在列出目录对象的文件,并将其推送到数组中,如果文件是目录本身.问题是,我的测试(File.directory?)的结果是否奇怪 – 这里是我的方法代码:

def subdirs
    subdirs = Array.new
    self.each do |x|
      puts "Evaluating file: #{x}"
      if File.directory?(x)
        puts "This file (#{x}) was considered a directory by File.directory?"
        subdirs.push(x)
        #yield(x) if block_given?
      end
    end
    return subdirs
  end

奇怪的是,即使目录中有很多目录(“/ tmp”) – 此调用的结果仅列出“.”.和“..”

puts "Testing new Directory custom class: FileOps/DirClass"

nd   = Directory.new("/tmp")
subs = nd.subdirs

结果:

Evaluating file: mapping-root
Evaluating file: orbit-jvxml
Evaluating file: custom-directory
Evaluating file: keyring-9x4JhZ
Evaluating file: orbit-root
Evaluating file: .
This file (.) was considered a directory by File.directory?
Evaluating file: .gdmFDB11U
Evaluating file: .X0-lock
Evaluating file: hsperfdata_mishii
Evaluating file: .X11-unix
Evaluating file: .gdm_socket
Evaluating file: ..
This file (..) was considered a directory by File.directory?
Evaluating file: .font-unix
Evaluating file: .ICE-unix
Evaluating file: ssh-eqOnXK2441
Evaluating file: vesystems-package
Evaluating file: mapping-jvxml
Evaluating file: hsperfdata_tomcat

解决方法

您是否在/ tmp内执行脚本?我的猜测(我还没有尝试过)是File.directory?(x)测试当前目录中是否有一个名为x的目录 – 所以如果你从另一个目录运行,总是找到.而不是其他目录.

尝试将File.directory?(x)更改为File.directory?(“#{path}/#{x}”).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读