jayson
1
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
2
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
jayson
3
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
jayson
5
This is working
Thanks
Jayson
jayson
6
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
}