There are two ways to use File.open:
1) the one you may be familiar with, like
my_file = File.open("songdata")
s = my_file.read
my_file.close
2) the second that takes a block
File.open("songdata") do |my_file|
s = my_file.read
end
#open calls the block only one time (there is
nothing to iterate here) passing in the file object
it would have returned if called without the block.
Why? because it's a nice way of resource handling.
After calling the block #open closes the file. You
can't forget to call close.
cheers
Simon
> -----Original Message-----
> From: Jurgen Stroo [mailto:blurg / JurgenStroo.com]
> Sent: Thursday, September 22, 2005 10:16 AM
> To: ruby-talk ML
> Subject: Argument passing with |boofar| (fwd)
>
> Lo Fellow listers,
>
> I already mentioned I am starting to learn Ruby the last
> couple of days.
> I came across the following in the Prog. Ruby book:
>
> File.open("songdata") do |song_file|
> songs = SongList.new
> song_file.each do |line|
> file, length, name, title = line.chomp.split(/\s*|\s*/)
> songs.append(Song.new(title,name,length))
> end
> puts songs[1]
> end
>
> I previously read about the argument passing between methods and code
> blocks. They used explanations of this construct which were
> indeed clear
> to me:
>
> ('a'..'e').each {|char| print char}
>
> this each method is of course iterating over the list and
> returning the
> value each time for each list entry, which is passed as the variable
> 'char' in the block. (correct me if I'm wrong)
>
> But, in the case of:
>
> File.open("songdata") do |song_file|
>
> what is returned then? I mean, the File.open is just a
> statement without a
> return value, or isn't it?
>
> I hope someone can explain me the inner workings of the given example
> which is not clear to me.
>
> Many thanks,
> Jurgen
>
>
>