The Ruby forum is hot, hot today!
An avid Rubyist proposes a very interesting #as method. It definitely looks rubyesque, but others disagree, namely James Gray and a bright fellow named Ara.
The original posting that generated a lot of good debate on the merits of such an approach.
I don’t mean to be sensational about it, but the code presented by Ara was simply gorgeous. It reeked of solid programming and, more importantly, a fundamental understanding that if you’re resorting to “neat tricks,” you your code needs to be smothered into submission.
That said, I still like the idea of #as. It’s different, and there are some drawbacks (mentioned on the forum), but I think it’s worth feeling out. It’s easy as hell to implement:
class Object def as yield(self) end end
So it’s worth trying.
Here are the two examples in question.
Ara’s suggestion (”traditional” method, in my mind):
guesses = stems.map{|stem| "#{ stem }.#{ guess_extension stem }"} basenames = transform2 source_files + transform1(guesses) expanded = basenames.map{|basename| File.join dir basename}
FC’s suggestion with #as:
expanded = stems.map { |stem| "#{ stem }.#{ guess_extension stem }" }.as { |guesses| transform2(source_files + transform1(guesses)) }.as { |basenames| basenames.map { |basename| File.join dir, basename } }
Now, I will not use curly braces for multi-line blocks. Forget about it. Here’s what it looks like with do…end.
expanded = stems.map do |stem| "#{ stem }.#{ guess_extension stem }" end.as do |guesses| transform2(source_files + transform1(guesses)) end.as do |basenames| basenames.map do |basename| File.join dir, basename end end
Not so pretty, is it? It’s definitely less sentence-like than with curly braces.
In the end I suppose it comes down to style and being flexible. If I were so dead-set against { and } for multi-line blocks I could definitely see using it. On the other hand I question my conviction in that area… is it worth missing out on a potentially useful feature just to follow dogma?
Programming. It’s definitely an art.