Problem with Files

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

On Sun, Aug 14, 2011 at 4:37 PM, amir e. [email protected] wrote:

On Sun, Aug 14, 2011 at 4:55 PM, John-John T.
[email protected]wrote:

and please explain me what is the difference between that code and below
Posted via http://www.ruby-forum.com/.

Accidentally hit “Send”.

The first form is when “open” is called with a block.
For File#open:
http://www.ruby-doc.org/core/classes/File.html#M000069

The second form utilizes the “each” method in the IO class.
http://www.ruby-doc.org/core/classes/IO.html

– John-John T.

On Sun, Aug 14, 2011 at 9:37 AM, amir e. [email protected] wrote:

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