Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away