开发者

Alphabetize results of Dir.glob

In my controller I have:

@files = Dir.glob("public/downloads/*")

In my view I have:

<% @files.each do |f| -%>
    <p><%= f.split("#{RAILS_ROOT}/public/downloads/")%>开发者_如何学Python;</p>
<% end -%>

How can I put the results in alphabetical order?


You should be able to just:

@files = Dir.glob("public/downloads/*").sort


The order of the array Dir.glob returns depends on the operating system you use, as the the documentation states. On most computers, this is the order you'd expect, but for example on heroku the order is pretty arbitrary.

You can just sort the array by chaining sort to your existing method call (Dir.glob("public/downloads/*").sort), as the first answer suggested. However, if you use the method multiple times, it may be more convenient to create an around alias in order for Dir.glob to always return an ordered array:

class Dir
  class << self
    alias :original_glob :glob

    def glob(*args)
      original_glob(*args).sort
    end
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜