Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does delete return the deleted element instead of the new array?

Tags:

ruby

In ruby, Array#delete(obj) will search and remove the specified object from the array. However, may be I'm missing something here but I found the returning value --- the obj itself --- is quite strange and a even a little bit useless.

My humble opinion is that in consistent with methods like sort/sort! and map/map! there should be two methods, e.g. delete/delete!, where

ary.delete(obj) -> new array, with obj removed
ary.delete!(obj) -> ary (after removing obj from ary)

For several reasons, first being that current delete is non-pure, and it should warn the programmer about that just like many other methods in Array (in fact the entire delete_??? family has this issue, they are quite dangerous methods!), second being that returning the obj is much less chainable than returning the new array, for example, if delete were like the above one I described, then I can do multiple deletions in one statement, or I can do something else after deletion:

ary = [1,2,2,2,3,3,3,4]
ary.delete(2).delete(3)      #=> [1,4], equivalent to "ary - [2,3]"
ary.delete(2).map{|x|x**2"}  #=> [1,9,9,9,16]

which is elegant and easy to read.

So I guess my question is: is this a deliberate design out of some reason, or is it just a heritage of the language?

like image 253
xzhu Avatar asked Oct 30 '25 09:10

xzhu


1 Answers

If you already know that delete is always dangerous, there is no need to add a bang ! to further notice that it is dangerous. That is why it does not have it. Other methods like map may or may not be dangerous; that is why they have versions with and without the bang.

As for why it returns the extracted element, it provides access to information that is cumbersome to refer to if it were not designed like that. The original array after modification can easily be referred to by accessing the receiver, but the extracted element is not easily accessible.

Perhaps, you might be comparing this to methods that add elements, like push or unshift. These methods add elements irrespective of what elements the receiver array has, so returning the added element would be always the same as the argument passed, and you know it, so it is not helpful to return the added elements. Therefore, the modified array is returned, which is more helpful. For delete, whether the element is extracted depends on whether the receiver array has it, and you don't know that, so it is useful to have it as a return value.

like image 182
sawa Avatar answered Nov 03 '25 00:11

sawa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!