ruby picture

RCR 230: 'for' for multiple arrays

Submitted by mchase (Fri Mar 12 20:03:27 UTC 2004)

Abstract

Give syntax for using the 'for' shortcut on multiple arrays.

Problem

Iteration over multiple enumerables at once is not simple or intuitive, involving explicit indexing into each of the enums (fine for people who came from C), and what is being iterated over is not well described by the loop control of the iteration (for example: '[a.length, b.length].max.times do |i| puts a[i],b[i] end').

Proposal

Allow comma delimited list of Enumerables to be zipped together and iterated over.

for x,y,z in enum_1,enum_2,enum_3
  puts x,y,z
end
would be a shortcut to
enum_1.zip(enum_2, enum_3).each do |x,y,z|
  puts x,y,z
end

Analysis

The shortcut wouldn't carry over and be able to help the normal use of #each, as 'for' is already doing some magic, and it would have to be doing more with this.

To be able to mix Hashes, Arrays, &c., further magic would have to happen, such as calling #to_a on all enums passed as arguments to #zip (possibly moving that behavior to #zip itself).

Implementation

*pending grokery of parse.y*
ruby picture
Comments Current voting

It's hard to argue naturalness in the abstract (I won't even try :-) but in the context of Ruby, iterating through an Enumerable object with #each is a bread-and-butter technique. It's debateable whether 'for' has the feel of something slightly out of keeping with idiomatic Ruby, but I don't think there's any chance that #each does :-) -- David Black


It's already possible to iterate over a hash with for:

  h = {"a"=>100, "b"=>200}
  for (k, v) in h
    print k, " is ", v, "\n"
  end

Sam's proposol would also be at odds with this RCR.

I would dream of the possibility to have a better version of zip in Ruby. The current version has the disadvantage to build (probably large) temporary arrays, and this behaviour would be masked even more if the for syntax is extended like this RCR proposes it. In my dream version zip would use generators to fetch values from the enum arguments of zip, without building temporary arrays. It's easy to implement a zip with the ruby generator module, but using this zip is painfully slow (ruby continuations are pretty slow), so the current version is much faster even for big temporary arrays.

So, I like the extended for syntax, but fear the current implementation problems.

-- Florian Frank


Strongly opposed 1
Opposed 9
Neutral 0
In favor 5
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 .