こんにちは。鈴木教郎です。
原さんのコードに刺激されて、こんなの書いてみました。
始めに相補する単語から hash をつくっておくという方法です。
#!/usr/local/bin/ruby
class Completion
def initialize(list)
# var for completion items.
@complete_list = {}
# check each list item
list.each{|word|
print "#{word} ->\n" if $DEBUG
# match from head to make completion list
for letter_counter in 1 .. word.size
letter = word[0, letter_counter]
print "\t#{letter} -> " if $DEBUG
# skip if already checked
if @complete_list[letter]
print "skipped\n" if $DEBUG
next
end
# make comletion list
array = []
list.each{|item|
if item =~ /^#{letter}/
array.push(item)
end
}
@complete_list[letter] = array
print "matched to ", array.join(", "), "\n" if $DEBUG
end
}
end
def complete(key)
@complete_list[key]
end
end
list = Completion.new(["when", "which", "what", "where", "who", "how"])
while true
print "INPUT: "
item = readline.chop
result = list.complete(item)
if result
print "#{item} -> ", result.join(", "), "\n"
else
print "no item #{item}\n"
end
end
--
鈴木教郎
E-Mail: nosuzuki / e-mail.ne.jp