mko
mko

Reputation: 22064

Why does File.each work but File.readline doesn't?

Why does File.each work but File.readline doesn't?

File.open('store-sample','r') do |f|

  f.readline("\n\n\n\n") do |l|
    binding.pry

  end
end

The code doesn't break however the following code works:

File.open('store-sample','r').each("\n\n\n\n") do |l|
  binding.pry
end

I don't know the internal implementation of these two methods, but this weird behavior really makes me crazy.

Upvotes: 1

Views: 169

Answers (2)

the Tin Man
the Tin Man

Reputation: 160551

Why don't you use File.foreach? It's designed to return a single line at a time.

Upvotes: 1

Josh Lee
Josh Lee

Reputation: 177584

readline doesn’t take a block; it returns a value.

line = f.readline('\n\n\n\n')
# do something with line

Upvotes: 3

Related Questions