Enumerable still…

Still playing around with Enumerables. It was almost not worth mentioning, but it’s a short post. I was looking for a short way to read in a file’s contents all into memory all at once. Normally you wouldn’t do this, because it eats up memory if you do it this way. But my files were short.

File.open('README', 'r') do |file|
file.inject { |contents, line| contents << line }
end

This will open up a file README and return the entire contents as a string. It’s pretty cool, since I don’t have to muck around with temporary variables much…and it’s readable…well, if ‘inject’ makes sense to you. Also cool is that, like Java container classes, as long as you implement ‘each’ in your Ruby class, you get all the ones in Enumerable for free. You just have to include it.


Wilhem has built Annologger, a tool that lets people worship your dentist appointments.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s