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

···

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

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/\.

···

On Sun, Aug 14, 2011 at 4:37 PM, amir e. <aef1370@gmail.com> 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

···

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/\.

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 Tedro

···

On Sun, Aug 14, 2011 at 4:55 PM, John-John Tedro <johnjohn.tedro@gmail.com>wrote:

On Sun, Aug 14, 2011 at 4:37 PM, 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/\.