Submitted by mchase (Fri Mar 12 20:03:27 UTC 2004)
Give syntax for using the 'for' shortcut on multiple arrays.
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
').
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
endwould be a shortcut to
enum_1.zip(enum_2, enum_3).each do |x,y,z|
puts x,y,z
end
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).
Comments | Current voting | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
|
RCRchive copyright © David Alan Black, 2003-2005.
Powered by .
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:
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