--bcaec54ee99efb121304aa7a83e6
Content-Type: text/plain; charset=ISO-8859-1

On Sun, Aug 14, 2011 at 9:37 AM, amir e. <aef1370 / gmail.com> wrote:

> Hi
> I don't understand meaning of thing that , this code return :
>
> File.open("a.txt")do |i|
>  puts i
> end
>
> please explain me.
> and please explain me what is the difference between that code and below
> code :
>
> File.open("a.txt").each do |i|
>  puts i
> end
>
>
> thanks
>
> --
> Posted via http://www.ruby-forum.com/.
>
>
The first version, File.open will open the file, then pass it into the
block, where you try to print it (but you're printing the file object
itself, rather than the contents of the file), then after calling the block,
it will close the file.

The second version will open the file, then iterate over each of its lines,
printing them out. But since you didn't pass a block, File.open doesn't
close the file for you, and since you aren't doing it, it never gets closed.

In short, neither of these are what you want. Use File.foreach (assuming
you're trying to iterate over lines)

File.foreach "a.txt" do |i|
 puts i
end

--bcaec54ee99efb121304aa7a83e6--