Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/")%></p>
<% end -%>

How can I put the results in alphabetical order?

like image 715
Jay Avatar asked Jan 27 '11 08:01

Jay


2 Answers

You should be able to just:

@files = Dir.glob("public/downloads/*").sort
like image 144
re5et Avatar answered Oct 22 '22 11:10

re5et


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
like image 27
gitcdn Avatar answered Oct 22 '22 11:10

gitcdn