HTMLファイルを集めてindex.htmlを作る

っていうRubyスクリプトを結城(るびこ)さんが書いているのを見つけた -> HTMLファイルを集めてindex.htmlを作る - rubyco(るびこ)の日記。実はつい一昨日あたりに僕も似たような目的でスクリプトを書いている。比べてみると違いがよく分かる。

僕の↓

#!/usr/local/bin/ruby

def header
  print "Content-Type: text/html\n\n"
  puts "<html>"
  puts "<head><title>index</title></head>"
  puts "<body>"
end

def footer
  puts "</body>"
  puts "</html>"
end

header()

Dir::foreach('.') {|f|
  if ( /\.(cgi)|(html)$/ =~ f )
    puts "<a href=\"#{f}\">#{f}</a><br>"
  end
}

footer()

一番頭のところにあるおまじないみたいな一行を shebang と呼ぶことを最近知った。メインの部分では、カレントディレクトリにあるファイルを一つずつ見ていって、それらの拡張子を正規表現で調べている。cgi または html だったらリンクをつくる。
結城さんの↓

require 'pathname'

index = Pathname.new("index.html")
index.open("w") do |out|
  out.puts "<html><body><ul>"
  Pathname.glob("*.html").sort.each do |file|
    next if file == index
    out.puts %Q(<li><a href="#{file}">#{file}</a></li>)
  end
  out.puts "</ul></body></html>"
end

結城さんは Pathname なるモジュールを使っている。ファイル操作をするときはこのモジュールを使った方がスマートな記述ができる模様。覚えておこう。