Neat Ruby Tricks: File.open Return Values

Back when I started using Ruby I would often read in data from a file as follows

1 file = File.new( 'data.txt' )
2 parsed_data = parse( file )
3 file.close

Later I switched to using File.open which handles closing the file for you

1 parsed_data = nil # Required otherwise parsed_data will be nil outside the block
2 File.open( 'data.txt' ) do |file|
3   parsed_data = parse( file )
4 end

Recently I realised, and felt pretty stupid for not having realised it earlier, that File.open will return the last expression evaluated in it’s block. Which means the above can be rewritten as

1 parsed_data = File.open( 'data.txt' ) do |file|
2   parse( file )
3 end

or as a much more elegent single line version (and now my preferred method)

1 parsed_data = File.open( 'data.txt' ){ |file| parse( file )}

Farrel Lifson is a lead developer at Aimred.

About Aimred

Aimred is a specialist Ruby and Ruby on Rails development house and consultancy based in Cape Town, South Africa.

We provide Ruby and Ruby on Rails development, consulting and training services to businesses and organisations of all sizes. If you want to find out how we can help you, contact us at info@aimred.com.

Recent Posts

Yearly Archives