Dir.entries(src).sort.each 做 |item|按自然顺序

时间:2021-08-01 19:47:41

标签: ruby macos sorting

文件名看起来像 1835 Some text. p11835 Some text. p10351835 Some text. p2

我希望以自然顺序处理文件,但 Ruby 以二进制顺序排序,因此 p1035 排在 p2 之前。这可以使用 Dir.entries(src).sort.each do |item| 之类的东西按自然顺序完成吗?

我想处理 .jpg 文件并根据 p(age) 顺序更改创建日期。例如,上述文件的创建日期为 1897-01-01 00:00:**01** -08001897-01-01 00:00:**02** -0800 等。也就是说,秒数递增,因此它们在照片管理程序中按顺序出现,并在该程序的日历中显示。< /p>

在 macOS 上

2 个答案:

答案 0 :(得分:1)

是的,您可以使用 naturally

$ gem install naturally
Fetching naturally-2.2.1.gem
Successfully installed naturally-2.2.1
Parsing documentation for naturally-2.2.1
Installing ri documentation for naturally-2.2.1
Done installing documentation for naturally after 0 seconds
1 gem installed

$ irb
2.7.4 :001 > require 'naturally'
 => true 
2.7.4 :002 > Naturally.sort(['1835 Some text. p1', '1835 Some text. p1035', '1835 Some text. p2'])
 => ["1835 Some text. p1", "1835 Some text. p2", "1835 Some text. p1035"] 
2.7.4 :003 > Naturally.sort(["336", "335a", "3356", "335.1"])
 => ["335.1", "335a", "336", "3356"] 

答案 1 :(得分:0)

添加到@Schwern

Dir.chdir(src)  # the directory
files = Dir.glob("*.{jpg,png}")
filesSorted = Naturally.sort(files)
filesSorted.each do |item|
  fn = src + item
  # process each file
end

这比 Dir.entries(src).each 有一点优势,因为 Dir.glob 似乎没有选择 .和 .. 文件。