«

»

Sep 11

universal cat redux

I have a neglectful relationship with inject. That is, I neglect to remember that it exists, having worked for so long with other languages which are “unfamiliar with the concept”. Amos King’s blog entry on Inject & Me – BFFs got me to thinking that ucat (see cat on steroids (or cat on a hot ruby roof)) could use inject as opposed to the each_byte. So, instead of

I can do:

I still think there needs to be a better way — going from string to an array of strings mapped to an array of bytes so that I can process it via inject seems to be awkward. So, I do some searching and find Object#enum_for (let me plug gotAPI — it’s a great tool for searching a large number of API’s) and come up with:

That seems cleaner to me. One of the things I love about ruby is that there’s usually more way than one to do something. And it’s often quicker, like in Unix, to go with what you know rather than making it more elegant. However, I also like that it’s easy to write elegant code.

And elegant code is a thing of beauty.

You can download the updated version of ucat.rb (you may need to rename it to ucat.rb)

2 comments

  1. Nit Khair

    Could you pls explain how the 3rd is clearer or more elegant than the first.

    I am easily able to follow the first, I am a tad lost with the other 2. Would it not take most people more time to figure out … I am a newbie, forgive me if its easy for most rubyists.

    Thanks.

  2. Matt Williams

    I’m thinking that inject is clearer in some ways because it isn’t needing an extra variable to be declared outside of the loop and then explicitly returned.

    The 2nd method certainly is kludgy, I think. Getting at the contents of the string takes some work. Of the 2nd and third methods, I prefer the third — for one thing, there’s a lot less method chaining going on.

    Part of the point, I think was that there’s more than one way to write the code and some may be more efficient and/or elegant than others. The first version certainly works, I just feel that having to declare variables outside of the loop and return it explicitly seems awkward. Of course, the each_byte method is pretty nice, but I don’t know that it makes up for the extra work. It’s far too easy to forget to return the value of the external string, methinks.

Leave a Reply

%d bloggers like this: