Ruby 初心者スレッド Part 33
at TECH
62:デフォルトの名無しさん
09/12/08 14:29:56
>>61
こう囁く
「なー、そのsaveするときの文字列がクラス本体にpとか追記せずに画面に表示できたら便利だと思わね?」
そしてこうする
class Publisher
def initialize(p)
@text, @from, @to, @path = p[:text], p[:from], p[:to], p[:path]
end
def publish
output = replace(@text, @from, @to)
save(io, output)
end
def io
case @path
when IO, File then @path
when "$stdout", nil then $stdout
when "$stderr" then $stderr
else File.open(@path, 'wb')
end
end
def replace(text, from, to); text.gsub(/#{from}/){to}; end
def save(io, str); io.print(str); io.close if io.kind_of?(File); end
end
Publisher.new(:text => 'ruby大好き!', :from => 'ruby', :to => 'オブジェクト指向スクリプト言語Ruby', :path=> $stdout).publish
これなら Publisher#save に StringIO を渡せばテストできるはず
保存時ファイル操作のエラーのときに独自処理したい場合はこれでは駄目だけど
次ページ続きを表示1を表示最新レス表示スレッドの検索類似スレ一覧話題のニュースおまかせリスト▼オプションを表示暇つぶし2ch
5501日前に更新/233 KB
担当:undef