Can you terminate an each_line statement.

J

Jayson Williams

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
 
7

7stud --

Jayson said:
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
 
7

7stud --

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
 
J

Jayson Williams

How is

file.each_line do |var|

...
break
end

handled differently from

file.each_line{|var|

...
break
}
 
7

7stud --

Jayson said:
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
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top