为什么Ruby似乎可以随机访问目录中的文件? [英] Why does Ruby seem to access files in a directory randomly?

查看:76
本文介绍了为什么Ruby似乎可以随机访问目录中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这是代码:

  class FileRenamer 
def RenameFiles(folder_path)
files = Dir.glob(folder_path +/ *)
end
end

puts重命名文件...

renamer = FileRenamer.new()
files = renamer.RenameFiles(/ home / papuccino1 / Desktop / Test)
放置文件

放重命名完成。

似乎是提取文件是随机顺序,而不是在Nautilus中显示。 p>



这是按设计吗?我只是好奇。

解决方案

订单在每个特定的操作系统上都应该是一样的,但是它是



行为或Dir.glob不能依赖于不同的操作系统。不确定这是否是设计的,而是文件系统的文件。



在Windows和Linux上,结果按层次结构排序,然后按字母顺序排列;在Mac OS X上,结果按字母顺序排列。



您可以通过调用排序结果来减轻效果,例如:

  files = Dir.glob(./*)。sort 

或者如果你想不区分大小写,可能:

  files = Dir.glob(./*)sort {| a,b | a.upcase< => b.upcase} 


Is this by design?

Here's the code:

class FileRenamer
    def RenameFiles(folder_path)    
        files = Dir.glob(folder_path + "/*")
    end
end

puts "Renaming files..."

renamer = FileRenamer.new()
files = renamer.RenameFiles("/home/papuccino1/Desktop/Test")
puts files

puts "Renaming complete."

It seems to be fetching the files is random order, not as they are displayed in Nautilus.

Is this by design? I'm just curious.

解决方案

The order should be the same every time on a particular OS, however it is different across operating systems.

The behaviour or Dir.glob can not be relied upon to be the same across different OSs. Not sure if this is by design, but rather an artefact of the filesystems.

On Windows and Linux the results are sorted by hierarchy, and then alphabetically; On Mac OS X the results are sorted alphabetically.

You could mitigate the effect by calling sort on your results e.g.:

files = Dir.glob("./*").sort

or if you wanted it case insensitive, perhaps:

 files = Dir.glob("./*").sort {|a,b| a.upcase <=> b.upcase}

这篇关于为什么Ruby似乎可以随机访问目录中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆