Hi --

On Thu, 20 Apr 2006, Nathan Olberding wrote:

> Yukihiro Matsumoto wrote:
>> I'm not sure what you mean by the word "right" here.  It's ok for you
>> to write that kind of program, but I don't (can't) guarantee you will
>> get what you expect, although I try my best.  It might cost you much
>> to guarantee loop safety.  It shouldn't crash in any case though.
>
> Though I was confused for half of the day today, I have to admit that
> the current implementation is probably for the best. Where this:
>
> arr.each do |x|
>    if y; arr.delete(x); end
> end
>
> Can be made to work the way I personally thought it would, it's much
> safer to do something like this:
>
> delete_list = []
> arr.each do |x|
>    if y; delete_list.push(x); end
> end
> arr -= delete_list
>
> Or better yet, since Ruby includes the feature, use Array#delete_if.

Also, don't forget (among reasons deleting from an array during an
iteration is bad) that delete deletes all instances:

irb(main):027:0> a = [1,2,3,1,4,5,1,6,7]
=> [1, 2, 3, 1, 4, 5, 1, 6, 7]
irb(main):028:0> a.delete(1)
=> 1
irb(main):029:0> a
=> [2, 3, 4, 5, 6, 7]    # all the 1's deleted

Also, something like each_with_index would probably cease to make
sense....


David

-- 
David A. Black (dblack / wobblini.net)
Ruby Power and Light, LLC (http://www.rubypowerandlight.com)

"Ruby for Rails" PDF now on sale!  http://www.manning.com/black
Paper version coming in early May!