わたなべです。 しん <dezawa / aliadne.net> writes: > こんなscriptを通します。 > 期待は、Jan というファイルに Jan が3行、Feb というファイルに Febが1行 > 出ることなのですが、1行書いたところでエラーとなります。 > > $cat files.rb > alist = ["Jan","Jan","Jan","Feb","Mar","Apr","May","Dec"] > > ofile="" > alist.each{|file| > if ofile != file > ofile != "" && ofp.close > ofile = file > ofp = open(ofile,"w") > end > ofp.printf "%s\n",file > } > ofp.close > > $ruby files.rb > files.rb:6: undefined local variable or method `ofp' for main:Object (NameError) > from files.rb:4:in `each' > from files.rb:4 > > Jan というファイルに Jan と 1行書かれておわり。 > ofp が nil になってしまっています。 > > なぜでしょう、、、 ofpがnilじゃなくてundefineなところに注目してほしいんですが、 この場合のofpはブロックローカルな変数だからエラーになってます。 eachの前で代入が必要です。たとえばofp = nilのように。 -- わたなべひろふみ