LoginSignup
1
1

More than 5 years have passed since last update.

gets,readlineは行の途中まででもも読んじゃう

Last updated at Posted at 2015-02-18

tailっぽく1行づつ読みたい

gets.rb
output = open("file.txt","w")
output.sync = true

Thread.new do
  open("file.txt") do |f|
    loop do
      if f.eof?
        sleep 0.01
      else
        s = f.gets #readline
        puts "gets: #{s.inspect}"
      end
    end
  end
end

output.puts("line01")
sleep(0.1)

output.write("line02\nline03\nline04\n")
sleep(0.1)

output.write("lin")
sleep(0.1)
output.write("e05\n")
sleep(0.1)

output.flush
sleep(1)

=begin
gets: "line01\n"
gets: "line02\n"
gets: "line03\n"
gets: "line04\n"
gets: "lin"
gets: "e05\n"
=end

tailer

def tailer(input)
  Enumerator.new do |y|
    buf = ""
    loop do
      if input.eof?
        sleep 0.1
      else
        buf << input.read(4*1024)
        while buf =~ /(.*?\n)(.*)/m
          y << $1
          buf = $2
        end
      end
    end
  end
end

open(ARGV[0]) do |f|
  tailer(f).each do |line|
    puts line
  end
end
1
1
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
1