はじめまして。
土岐といいます。
ruby で UNIX の look コマンドを作りたくて、perl のライブラリに入ってる
look.pl を ruby に翻訳したんですが、IO クラスの内側での pos= メソッド
の挙動がなんか変です。
class IO
def look(key, dict = false, fold = $=)
s = stat
size = s.size
blksize = s.blksize
raise "zero size exception!" unless size
blksize = 8192 unless blksize
key = key.gsub(/[^\w\s]/, "") if dict
key = key.downcase if fold
min = 0
max = size / blksize
while (max - min > 1)
mid = (max + min) / 2
pos=(mid * blksize)
$stdout.print "tell:#{tell}, pos:#{pos}\n" # debug
gets if mid # probably a partial line
l = gets
l.chomp!
l.gsub!(/[^\w\s]/, "") if dict
l.downcase! if fold
if (l < key) then
min = mid
else
max = mid
end
end
min *= blksize
pos=(min)
$stdout.print "tell:#{tell}, pos:#{pos}\n" # deubg
gets if min
while (l = gets)
l.chomp!
l.gsub!(/[^\w\s]/, "") if dict
l.downcase! if fold
break if (l >= key)
min = pos
end
pos=(min)
$stdout.print "tell:#{tell}, pos:#{pos}\n" # debug
end
end
こういうメソッドを IO クラスに追加したんですが、
試しに /usr/share/dict/words を "ruby" で検索すると
デバッグ用の出力はこうなります。
tell:0, pos:1236992
tell:4, pos:1859584
tell:11, pos:2170880
tell:21, pos:2326528
tell:35, pos:2400256
tell:50, pos:2441216
tell:68, pos:2457600
tell:87, pos:2465792
tell:95, pos:2473984
tell:107, pos:2473984
tell:1811096, pos:2473984
ちなみに、ruby のバージョンは 1.1c7(98/11/09) [i386-freebsd2.2.6] です。
メソッド定義の中で pos= を self.pos= or seek(offset, 0) に変更すると
tell:1236992, pos:1236992
tell:1859584, pos:1859584
tell:1548288, pos:1548288
tell:1703936, pos:1703936
tell:1777664, pos:1777664
tell:1818624, pos:1818624
tell:1794048, pos:1794048
tell:1802240, pos:1802240
tell:1810432, pos:1810432
tell:1810432, pos:1810432
tell:1811091, pos:1811091
となり正常に動作します。pos= はデフォルトで self を見に行くはずだから
わざわざ明示的に書く必要はないはずだし、そもそも self を指定しないとき
の動作が意味不明です。pos= メソッドは Maling List のアーカイブで検索し
ても ruby の附属ライブラリを grep しても出て来なかったので、あまり使
われてないみたいですが、これってひょっとしてバグですか?
----------------------------------------------------------------------
土岐 仁謙
神戸大学自然科学研究科前期博士課程物理学専攻高エネルギー物理学講座
Yoshinori Toki
HEP, Department of Physics, Faculty of Science, Kobe University
TEL: +81 (78) 803 0543
FAX: +81 (78) 803 0724
URL: http://www.phys.sci.kobe-u.ac.jp/~toki/toki.html
Email: toki / hep.phys.sci.kobe-u.ac.jp (public)
Email: toki / freedom.ne.jp (private)
PGP fingerprint = D0 A8 90 AB 73 F8 34 FE CE CA DB BF 01 30 C0 35