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

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)

It's iterating over the range, not the list; but that's a minor point.

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?

It's yielding the file object itself, which you can work with, and will be automatically closed when the block finishes.

···

On 22-Sep-05, at 4:15 AM, Jurgen Stroo wrote:

Jurgen

--
Jeremy Tregunna
jtregunna@blurgle.ca

"If debugging is the process of removing bugs, then programming must be the process of putting them in." --Dykstra