sort_by and directories

Discussion in 'Ruby' started by Dafydd Fontenot, Apr 28, 2009.

  1. 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?
    --
    Posted via http://www.ruby-forum.com/.
     
    Dafydd Fontenot, Apr 28, 2009
    #1
    1. Advertising

  2. Hi,

    At Tue, 28 Apr 2009 11:42:07 +0900,
    Dafydd Fontenot 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("/")}

    --
    Nobu Nakada
     
    Nobuyoshi Nakada, Apr 28, 2009
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Michael Gaunnac

    A sort_by descending sort

    Michael Gaunnac, Oct 8, 2004, in forum: Ruby
    Replies:
    8
    Views:
    186
    Brian Candler
    Oct 9, 2004
  2. Patrick Gundlach

    stable sort_by?

    Patrick Gundlach, Dec 13, 2005, in forum: Ruby
    Replies:
    11
    Views:
    210
    Martin DeMello
    Dec 14, 2005
  3. Pat Maddox

    sort_by{rand} doesn't shuffle array

    Pat Maddox, Jan 3, 2006, in forum: Ruby
    Replies:
    4
    Views:
    136
    Mauricio Fernandez
    Jan 3, 2006
  4. Eric Hodel

    #sort_by and #sort_obj

    Eric Hodel, Oct 7, 2007, in forum: Ruby
    Replies:
    17
    Views:
    179
    Eric Hodel
    Oct 8, 2007
  5. Ron Smith
    Replies:
    5
    Views:
    165
    Michele Dondi
    Nov 2, 2004
Loading...

Share This Page