SVX日記

2004|04|05|06|07|08|09|10|11|12|
2005|01|02|03|04|05|06|07|08|09|10|11|12|
2006|01|02|03|04|05|06|07|08|09|10|11|12|
2007|01|02|03|04|05|06|07|08|09|10|11|12|
2008|01|02|03|04|05|06|07|08|09|10|11|12|
2009|01|02|03|04|05|06|07|08|09|10|11|12|
2010|01|02|03|04|05|06|07|08|09|10|11|12|
2011|01|02|03|04|05|06|07|08|09|10|11|12|
2012|01|02|03|04|05|06|07|08|09|10|11|12|
2013|01|02|03|04|05|06|07|08|09|10|11|12|
2014|01|02|03|04|05|06|07|08|09|10|11|12|
2015|01|02|03|04|05|06|07|08|09|10|11|12|
2016|01|02|03|04|05|06|07|08|09|10|11|12|
2017|01|02|03|04|05|06|07|08|09|10|11|12|
2018|01|02|03|04|05|06|07|08|09|10|11|12|
2019|01|02|03|04|05|06|07|08|09|10|11|12|
2020|01|02|03|04|05|06|07|08|09|10|11|12|
2021|01|02|03|04|05|06|07|08|09|10|11|12|
2022|01|02|03|04|05|06|07|08|09|10|11|12|
2023|01|02|03|04|05|06|07|08|09|10|11|12|
2024|01|02|03|04|

2023-05-10(Wed) 再帰で悩みまくる

  ワケあって、再帰プログラムを書く必要が生じたのだが、ちっとも目的の結果が出せない。そもそも、再帰がうまく書けてない。あまりの書けなさに自らショックを受けるほどに書けない。

  何度か書いたことはあるのだが、ちょっと難しいのは確か。こうなったら、回り道ではあるが、よく知っている構造についてまず書いてみて、それをベースにすればいいのではないか。と思い、ファイル/ディレクトリ構造を表示する、プログラムを書いてみた。

#!/usr/bin/ruby
 
def find(path)
    entry = {
        :type   => false,
        :name   => path.last,
    }
    unless(FileTest.directory?(path.join('/')))
        entry[:type] = 'file'
    else
        entry[:type] = 'dir'
        entry[:entries] = []
        Dir.open(path.join('/')).each {|e|
            e =~ /^\./ and next
            entry[:entries] << find(path + [e])                 # 再帰
        }
    end
    return(entry)
end
 
def show(entry, n = 0)
    puts('%s%4s: %s' % ["\t" * n, entry[:type], entry[:name]])
    if(entry[:type] == 'dir')
        entry[:entries].each {|entry1|
            show(entry1, n + 1)                                 # 再帰
        }
    end
end
 
entry = find(['fileA'])
show(entry)
 
puts
 
entry = find(['dirB'])
show(entry)
$ ./recursive 
file: fileA
 
 dir: dirB
	file: fileC
	 dir: dirD
		file: fileE
		file: fileF
	file: fileG

  これが大当たりで、これをベースにしたら、あっという間に目的のプログラムに近いものが書けてしまった。なんつうか、齢を取るってこういうことだよなぁ。