[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Can you terminate an each_line statement.

Jayson Williams

10/14/2007 1:57:00 AM

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

5 Answers

7stud --

10/14/2007 2:09:00 AM

0

Jayson Williams 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
--
Posted via http://www.ruby-....

7stud --

10/14/2007 2:14:00 AM

0

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
--
Posted via http://www.ruby-....

Jayson Williams

10/14/2007 2:18:00 AM

0

How is

file.each_line do |var|

...
break
end

handled differently from

file.each_line{|var|

...
break
}


On 10/13/07, 7stud -- <bbxx789_05ss@yahoo.com> wrote:
> 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
> --
> Posted via http://www.ruby-....
>
>

7stud --

10/14/2007 2:34:00 AM

0

Jayson Williams 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
}

--
Posted via http://www.ruby-....

Jayson Williams

10/14/2007 2:37:00 AM

0

This is working
Thanks
Jayson

On 10/13/07, Jayson Williams <williams.jayson@gmail.com> wrote:
> How is
>
> file.each_line do |var|
>
> ...
> break
> end
>
> handled differently from
>
> file.each_line{|var|
>
> ...
> break
> }
>
>
> On 10/13/07, 7stud -- <bbxx789_05ss@yahoo.com> wrote:
> > 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
> > --
> > Posted via http://www.ruby-....
> >
> >
>
>