Sunday, March 04, 2007

Ruby Block

If you use Ruby for any thing more than a simple "hello world" program then you probably hit Ruby block and closure. I write a lot of Ruby code to process data files. This is an ideal way to open a text file and process all lines within it.

File.open("filename", "r") do |file|
file.each_line do |line|
# do something with the line
end
end

It automatically close the file when it reached the end of the file.

If you want to learn more about Ruby block then head over to Darwinweb and read Ruby Blocks as Closure.

No comments: