# Sort\_by and directories

**URL:** <https://www.ruby-forum.com/t/sort-by-and-directories/166639>\
**Category:** Ruby\
**Created:** [April 28, 2009, 4:42am UTC](https://www.ruby-forum.com/t/sort-by-and-directories/166639 "2009-04-28T04:42:04Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![dafydd](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/8491ac/32.png) [@dafydd](https://www.ruby-forum.com/u/dafydd)\
**Post date:** [April 28, 2009, 4:42am UTC](https://www.ruby-forum.com/t/sort-by-and-directories/166639/1 "2009-04-28T04:42:04Z")

</div>

On my system I have this small ruby script as a test to arrange files.  
I’m using “find” and trying to get the files sorted starting with the  
files the farthest away from the base folder first in the array (so the  
files nested in the most sub directories are first on the array).

Here’s what the script looks like  
test = Array.new

`find /folder/place -type f`.split("\n").each do |file|  
test.push(file)  
end

test.sort\_by { |file| file.gsub(/[^/]/, “”).length }  
puts test

However when I run the script the files are not actually organized any  
different than what find returns.

Can someone correct me on my methodology?

---

<div class="post-metadata">

**Author:** ![dafydd](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/8491ac/32.png) [@dafydd](https://www.ruby-forum.com/u/dafydd)\
**Post date:** [April 28, 2009, 5:34am UTC](https://www.ruby-forum.com/t/sort-by-and-directories/166639/2 "2009-04-28T05:34:18Z")

</div>

Hi,

At Tue, 28 Apr 2009 11:42:07 +0900,  
Dafydd F. wrote in [ruby-talk:335235]:

> Here’s what the script looks like  
> test = Array.new
> 
> `find /folder/place -type f`.split("\n").each do |file|  
> test.push(file)  
> end
> 
> test.sort\_by { |file| file.gsub(/[^/]/, “”).length }  
> puts test

Array#sort\_by returns sorted new array, but doesn’t change the  
receiver itself.

require ‘find’  
test = []  
Find.find("/folder/place") {|file| test.push(file) if  
File.file?(file)}  
puts test.sort\_by {|file| file.count("/")}
