ruby picture

RCR 217: Make for..end return something useful

Submitted by grenzi (Tue Feb 17 18:02:30 UTC 2004)

Abstract

At the moment, the for..end loop is just syntax sugar for an each() method. The suggestion is to make it work like map()+compact().

Problem

Actually, this is not a "problem". But it may turn into a new feature. the for..end syntax is there mostly as syntax sugar for each. You just use it to do some iterative job. Nobody actually uses the return value from it, cause it's just the Enumerable involved in the top.

Proposal

The suggestion is to make

    
 for i in enumer do
  puts i if i%2 ==1
 end 

    

work like:


    
 enum.map {|i|print i if i%2==1}.compact

    

Analysis

This change should not break compatibility . Nobody should rely on return values from for..end cause that is fixed, ad of 1.8.x .

By changin this, you get list comprehension-like features. If this RCR is accepted, we may have code like this:


    
 def select_p(list)
  for p in list: p if p.cond? end
 end

    

The for..end loop now actually returns something useful, and is not anymore just a duplication of each().

(actually, that would more look like generator expression as suggested for python 2.4, more than ZFLC)

Implementation

this change requires changes to the semantyc of the language, and have no implementation.

ruby picture
Comments Current voting

err, obviously it was 'puts' even on the second code box. And obviously the example with select_p() is already doable with just compact. Think it like

 for p in list: p.value if p.cond? end
g.renzi


Actually I would do your original select_p with select, not compact. All you'd have to do is:

list.select {|e| e.cond}
And the second one I would do like this:
list.select {|e| e.cond? }.map {|e| e.value}

(I know it has more characters, but I don't think that's an important point in this case.)

In general, I'd rather use (and encourage use of) Ruby's more Ruby-like list processing methods, than add a somewhat obscure functionality into 'for'. (Actually I'd be happy if 'for' disappeared, but that's another story :-)

David Black


My main objection is performance: since current uses don't use a return value for for..end each iteration creates a temporary array and data within it that is discarded immediately.

If one needs map one can use map/collect and it will be clear immediately what's happening there while people usually not expect to get something back from a for loop statement IMHO.

Robert Klemme


Strongly opposed 4
Opposed 5
Neutral 1
In favor 0
Strongly advocate 0
ruby picture
If you have registered at RCRchive, you may now sign in below. If you have not registered, you may sign up for a username and password. Registering enables you to submit new RCRs, and vote and leave comments on existing RCRs.
Your username:
Your password:

ruby picture

Powered by .