Forum: Ruby sort_by and directories

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ruby-er R. (Guest)
on 2009-04-28 06:42
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?
Nobuyoshi N. (Guest)
on 2009-04-28 07:34
(Received via mailing list)
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("/")}
This topic is locked and can not be replied to.