Can you terminate an each_line statement

Hi all,

Is there a way to terminate an each_line iteration before it iterates
through every line? For instance:

file = open(url)

file.each_line{|line|
found = true if if line.include?(‘string’)
break if found == true
}

Is it possible to to break out of the each_line statement if found is
true?

Thanks
Jayson

Jayson W. wrote:

Is there a way to terminate an each_line iteration before it iterates
through every line? For instance:

file = open(url)

file.each_line{|line|
found = true if if line.include?(‘string’)
break if found == true
}

Is it possible to to break out of the each_line statement if found is
true?

File.open(“data.txt”, “w”) do |file|
(1…5).each do |i|
file.puts(“line #{i}”)
end
end

File.open(“data.txt”) do |file|
file.each_line do |line|
puts line
break
end
end

–output:–
line 1

Or, you could do this:

IO.foreach(“data.txt”) do |line|
if line.include?(“3”)
break
end

puts line
end

–output:–
line 1
line 2

How is

file.each_line do |var|


break
end

handled differently from

file.each_line{|var|


break
}

This is working
Thanks
Jayson

Jayson W. wrote:

How is

file.each_line do |var|


break
end

handled differently from

file.each_line{|var|


break
}

Try it yourself:

File.open(“data.txt”, “w”) do |file|
(1…5).each do |i|
file.puts(“line #{i}”)
end
end

File.open(“data.txt”) {|file|
file.each_line {|line|
puts line
break
}
}

IO.foreach(“data.txt”) {|line|
if line.include?(“3”)
break
end

puts line
}