Argument passing with |boofar| (fwd)

J

Jurgen Stroo

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
 
J

Jeremy Tregunna

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.

--
Jeremy Tregunna
(e-mail address removed)

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,183
Messages
2,570,968
Members
47,517
Latest member
TashaLzw39

Latest Threads

Top