LoginSignup
1
0

More than 5 years have passed since last update.

Ruby で $stdin を変更しても ARGF が変更されない?

Last updated at Posted at 2012-12-26

\$stdin を StringIO にすると ARGF の対象 IO が変更されますが、ARGF.each_line を使用後は $stdin を変更しても ARGF の対象 IO が変更されなくて困っています。

require 'stringio'

ARGF.file                       # => #<IO:<STDIN>>

$stdin = StringIO.new("hoge")
ARGF.file                       # => #<StringIO:0x82da3cc>

$stdin = StringIO.new("piyo")
ARGF.file                       # => #<StringIO:0x82da214>
ARGF.each_line do |l|
  l                             # => "piyo"
end

$stdin = StringIO.new("hogepiyo")
ARGF.file                       # => #<StringIO:0x82da214>
ARGF.each_line do |l|
  l                             # => 
end

上のコードだと、\$stdin を StringIO.new("piyo") にして ARGF.each_line を使用すると、$stdin を StringIO.new("hogepiyo") に変更しても ARGF.file が変わらない (ARGF.each_line で "hogepiyo" を読むことができない) という問題です。

each_line で ARGF を読み込んだ後、$stdin を変更することで ARGF を変更する方法について、わかる方がいれば教えていただけると幸いです。

ちなみに、上記コードの実行環境は ruby 1.9.3p0 (2011-10-30 revision 33570) [i686-linux] です。

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0