recursive output of a directory and its sub-directories

Discussion in 'Ruby' started by Alexander Fleck, Jul 6, 2007.

  1. hi,
    I want to walk through a directory recursively.

    I have the follwing code:

    '
    #!/usr/bin/env ruby

    def search
    Dir.foreach(".\\") { |x|
    if File.directory?(x)
    search
    else
    open(x) do |file|
    file.each { |l| puts l}
    end
    puts x
    end
    }
    end

    search
    '

    I get a 'stack level too deep'-error. What does that mean and how can I
    avoid it?

    thanks,
    Alex.
     
    Alexander Fleck, Jul 6, 2007
    #1
    1. Advertising

  2. Alexander Fleck

    come Guest

    Hi,

    You reach this limit because you are stacking forever: your search
    method has no argument, so no recursion occures. You have to pass the
    path of the subdirectory to search into to the search method.

    Another (better) way is to use the "find" standard library of Ruby.

    require "find"

    Find.find(".") do |f|
    puts f
    end

    (I haven't tested this code but it should work).
    It will do the work for you.

    Regards,
    Come

    On 6 juil, 08:45, "Alexander Fleck" <> wrote:
    > hi,
    > I want to walk through a directory recursively.
    >
    > I have the follwing code:
    >
    > '
    > #!/usr/bin/env ruby
    >
    > def search
    > Dir.foreach(".\\") { |x|
    > if File.directory?(x)
    > search
    > else
    > open(x) do |file|
    > file.each { |l| puts l}
    > end
    > puts x
    > end
    > }
    > end
    >
    > search
    > '
    >
    > I get a 'stack level too deep'-error. What does that mean and how can I
    > avoid it?
    >
    > thanks,
    > Alex.
     
    come, Jul 6, 2007
    #2
    1. Advertising

  3. Antw: Re: recursive output of a directory and its sub-directories

    thanks,

    I now use the 'find' module.

    Alex.
     
    Alexander Fleck, Jul 6, 2007
    #3
    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. Joel Finkel
    Replies:
    0
    Views:
    499
    Joel Finkel
    Sep 12, 2003
  2. could ildg
    Replies:
    0
    Views:
    310
    could ildg
    Jun 28, 2005
  3. Replies:
    4
    Views:
    375
    Jonathan N. Little
    Jan 26, 2007
  4. Lawrence D'Oliveiro

    Death To Sub-Sub-Sub-Directories!

    Lawrence D'Oliveiro, May 5, 2011, in forum: Java
    Replies:
    92
    Views:
    2,083
    Lawrence D'Oliveiro
    May 20, 2011
  5. Ron Smith
    Replies:
    5
    Views:
    155
    Michele Dondi
    Nov 2, 2004
Loading...

Share This Page