I must confess to a lack of Ruby guru-ness. It would be a great tutorial if someone would be gracious enough to give a token-by-token (blow-by-blow sounds so violent) commentary on what Reimer just wrote. Thanks, Drew > -----Original Message----- > From: Reimer Behrends [mailto:behrends / cse.msu.edu] > Sent: Sunday, September 01, 2002 5:59 PM > To: ruby-talk ML > Subject: Re: Ruby aesthetics > > > Gavin Sinclair (gsinclair / soyabean.com.au) wrote: > [...] > > > I'll conclude with one (new) feature from Python that makes me green > > with envy: list comprehensions. For those who don't know what that > > means, here's an example: > > > Ruby: squares_less_than_10 = numbers.find_all{|i| i<10}.map{|i| i^2} > > > > Python: squares_less_than_10 = [x^2 for x in numbers if x < 10] > > That calls for a functional abstraction (functional abstraction is > essentially a fancy software engineering term for factoring out commonly > occuring code sequences into a procedure, function, or method of its > own) rather than a new language feature. This abstraction is most easily > added to Enumerable: > > module Enumerable > > # map all elements through a filtering block, keeping all the results > # that aren't nil. > > def condmap > result = [] > each do > | elem | > item = yield elem > result << item unless item.nil? > end > result > end > > end > > To be used as follows: > > squares_less_than_10 = numbers.condmap{|x| x**2 if x < 10 } > > In general, you do not want to expand the language when existing > abstraction mechanisms can already capture the same thing adequately and > with more room for customization. > > Reimer Behrends >