l'essentiel est invisible pour les yeux

Monday, February 19, 2007

[本] Best of Ruby Quizで知識活用能力を高めよう

If you stop and think about it, programming knowledge is nearly useless
by itself. What exactly are you going to create with all that expert
programming skill, if it’s all you have? The world needs only so many
text editors.
Best of Ruby Quizはこのようなイントロダクションから始まる。
Ruby Quizを一冊にまとめたこの本は頭の体操が大好きなプログラマにとって十分楽しめる一冊である。

Best of Ruby Quizの第一問目"MadLibs"を解いてみる。

次のような文章が与えられた時に、丸括弧内を質問してその答えで丸括弧内を置換し出力するという問題である。また、質問の答えは問題文中で再利用できる。:で区切られた場合には、コロン内のキーワードを全て質問し、:以前のキーワードの答えで置換し出力する。

Our favorite language is ((gem:a gemstone)). We think ((gem)) is
better than ((a gemstone)).


ユーザインタフェースの指定は特になく自由である。
WEBインタフェースがRuby Quizのサイトで提供されている。

Ruby Quiz Madlibs

ユーザインタフェースとしてコマンドラインインタフェースを使用して問題を解いてみた。

madlibs.rb

#!/usr/bin/env ruby

class MadLibs
attr_reader :template
attr_accessor :questions

def initialize(template)
@template = template
@questions = template.scan(/\(\(([^)]*?)\)\)/).flatten.inject({}) do |ret, val|
if val.index(':').nil?
ret[val] = ""
else
val.split(':').each {|q| ret[q] = ""}
end
ret
end
end

def run
@questions.each do |key, ans|
print "Give me #{key}. < "
@questions[key] = STDIN.gets.chop
@template.gsub!(%r{\(\((#{key})\)\)|\(\((#{key}:[^\)]*?)\)\)}, @questions[key])
end
print @template
end
end
if $0 == __FILE__
if ARGV[0].nil?
puts "Usage: ./madlibs.rb <template file>"
exit 1
end
template = File.open(ARGV[0], 'r').read
MadLibs.new(template).run
end


template.txt

Our favorite language is ((gem:a gemstone)). We think ((gem)) is better than ((a gemstone)).



実行結果

% ./madlibs.rb template.txt
Give me a gemstone. < Perl
Give me gem. < Ruby
Our favorite language is Ruby. We think Ruby is better than Perl.
%


高度な知識をたくさん持つプログラマ。
学習し得た知識も活用出来なければただの死知識となる。

エレガントに解く。
パフォーマンス重視で解く。
Cの拡張ライブラリで解く。
1つの問題でも解き方は自由です。

日常から知識の活用能力を磨いておく事で、現実の解決困難な問題に遭遇しても筋道を立て考える事ができます。また、解決困難な問題にはひらめきも必要です。
一日一問。Best Of Ruby Quizはどうですか?