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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With