Array#delete return value

  • Thread starter Guillaume Marcais
  • Start date
G

Guillaume Marcais

According to the following contrived example (and the documentation),
Array#delete returns the object passed as argument if a match is found
and deleted:

[gus@comp tmp]$ cat delete.rb
Toto = Struct.new("Toto", :a, :b)
class Toto; def ==(t); a == t.a; end; end
t1 = Toto.new(1, 2)
t2 = Toto.new(1, 3)
p t1 == t2
a = [t1]
p t1.id
p t2.id
p a.delete(t2).id
[gus@comp tmp]$ ruby delete.rb
true
578438406
578438356
578438356

It seems to me it would make more sense to return the object actually
removed from the array (t1 in the example instead of t2).

The behavior I would expect is as follow:

[gus@comp tmp]$ cat delete2.rb
class Array
def delete2(o)
i = index(o)
return nil if i.nil?
delete_at(i)
end
end

Toto = Struct.new("Toto", :a, :b)
class Toto; def ==(t); a == t.a; end; end
t1 = Toto.new(1, 2)
t2 = Toto.new(1, 3)
p t1 == t2
a = [t1]
p t1.id
p t2.id
p a.delete2(t2).id
[gus@comp tmp]$ ruby delete2.rb
true
663778146
663778096
663778146

Any thoughts on the matter.
Guillaume.
 
Y

Yukihiro Matsumoto

Hi,

In message "Array#delete return value"

|According to the following contrived example (and the documentation),
|Array#delete returns the object passed as argument if a match is found
|and deleted:

|It seems to me it would make more sense to return the object actually
|removed from the array (t1 in the example instead of t2).

But Array#delete method deletes ALL elements that equal to the
argument. Do you want it to return an array of deleted items?

matz.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top