Quiz #65, Principle of Great Surprise, and Array.delete sled

William J. wrote:

ar.delete_one_element!(nil)
Right results, wrong output…

class Array
(i = index(x)) && delete_at( i )
self
end
end

And here’s yet another version, similar to the ones already posted
though:

class Array
def delete_one! n
(i = index(n)) ? delete_at(i) : nil
end
end

On Feb 5, 2006, at 5:28 AM, William J. wrote:

This may not be of any use to you, but here’s a way to delete all
elements but the first:

class Array
def no_dup!( x )
(i = index(x)) && delete( x ) && insert(i,x)
self
end
end

Array.uniq!

???

James Edward G. II

On Sun, 5 Feb 2006, [ISO-8859-1] Simon Kröger wrote:

cheers

good points all. i can only guess

  • Array#- doesn’t raise an error since it can partially succeed/fail,
    in
    otherwords some of the elements might be removed while some are
    not: is
    this success or failure? also Array#- is defined as ‘set
    difference’ and,
    under that def not raising an error certainly makes good sense -
    the
    result is always what you asked for - even if it’s empty.

  • Array#clear shouldn’t raise an error, since the result after
    calling it
    always want you’d hoped for : an empty arrray.

  • Array#delete… well you got me there. nil is at least useful so
    one can
    do

    a.delete(elem) or raise “failed”

    otherwise you have no idea if the operation succeeded or not.

the thing with writing a Array#delete_first method that returns the
array is
that there’s absolutely no indication of success or, as in the case of
Array#clear, a guarantee of success.

in general i think methods basically fail into two categories

  • those that always succeed, Array#clear for example. these can
    simply
    return self.

  • those that might fail and need to either return nil or raise an
    exception
    to indicate this. raising is nice because you can chain.

it’s not clear to me why ‘delete_first’ would be in the first category
but i
think this is largely religious.

cheers.

-a

James Edward G. II wrote:

end

Array.uniq!

???

James Edward G. II

irb(main):008:0> a=[1,1,2,2,3,3]
=> [1, 1, 2, 2, 3, 3]
irb(main):009:0> a.no_dup!(2)
=> [1, 1, 2, 3, 3]
irb(main):010:0> a.uniq!(3)
ArgumentError: wrong number of arguments (1 for 0)
from (irb):10:in `uniq!’
from (irb):10
irb(main):011:0> a.uniq!
=> [1, 2, 3]

Array#uniq is “massively destructive”.

On Feb 5, 2006, at 8:50, [email protected] wrote:

in general i think methods basically fail into two categories
but i
think this is largely religious.

I think you’re confusing “failure” with something else. If I ask a
method to delete a “22” from an array that contains none of them, then,
as I see it, deleting nothing from the array is a correct, successful
response. If I care if there are any such elements in the array in
the first place I can easily (and succinctly)
if myArray.index(element)