tree.rb

Rubyの練習。しかし、センスないなぁ…


#!/usr/local/ruby/bin/ruby
class Node
attr_accessor :name, :depth

def initialize(path)
@path = File.expand_path(path)
@name = File.basename(@path)
@depth = @path.count("/")
end

def get_children unless @children
@children =

Dir.glob(@path + "/*") {|child|
if FileTest.directory?(child)
@children << Node.new(child)
end
}
end

return @children
end

def to_string(tabs=, branch="", strbuf="")
put_row(@name, tabs, branch, strbuf)
children = get_children

while child = children.shift
tabs.push(children.size > 0 ? "│" : " ")
branch = children.size > 0 ? "├" : "└"
child.to_string(tabs, branch, strbuf)
tabs.pop
end

return strbuf
end

private
def put_row(name, tabs, branch, strbuf)
head = tabs.clone
head.pop if head.size > 0
head << branch
strbuf << head.join + name + "\n"
end
end

root = ARGV.shift

if root && FileTest.exist?(root)
node = Node.new(root)
puts node.to_string
end