Dir.glob有排序问题

时间:2015-04-19 17:54:27

标签: ruby-on-rails ruby sorting filelist

在" Alphabetize results of Dir.glob"中,我使用sort按字母顺序获取文件列表:

Dir.glob("#{options[:path]}/**/*.jpg", File::FNM_CASEFOLD).sort { |file|

  dir, filename = file.match(/.+\/(.+)\/(.+)/).captures

  # ---cut---

}

没有sort它的效果很好,但是它失败并出现错误:

$ rake slides:import -- --user foo --path /bar/baz
(in /home/user/app_folder)
"baz/ - /bar/baz/DSC_4120.JPG - saved"
rake aborted!
ArgumentError: comparison of String with 0 failed
/home/footoo/footoo/lib/tasks/slides.rake:41:in `>'
/home/footoo/footoo/lib/tasks/slides.rake:41:in `sort'
/home/footoo/footoo/lib/tasks/slides.rake:41:in `block (2 levels) in <top (required)>'
/usr/local/rvm/gems/ruby-2.1.5/bin/ruby_executable_hooks:15:in `eval'
/usr/local/rvm/gems/ruby-2.1.5/bin/ruby_executable_hooks:15:in `<main>'
Tasks: TOP => slides:import

知道什么是错的吗?

Github上提供完整代码。

1 个答案:

答案 0 :(得分:4)

当sort给出一个块时,它希望它返回-1,0或1以便知道如何排序(自定义<=>函数)。您需要在排序后添加each以恢复默认排序和预期行为。

Dir.glob("#{options[:path]}/**/*.jpg", File::FNM_CASEFOLD).sort.each{|file|
....
}

请阅读此处的文档:http://ruby-doc.org/core-2.2.0/Array.html#method-i-sort