=begin
- Matz: As for the method name, phluid61's explanation is exactly what I had in mind. And, some use cases are as shown below.
- phluid61: Your implementation looks perfect to me.
==== Use case 1
I want to delete and get from an array a
an element at position i
if there is such element. That element can be possibly nil
.
With index?
, it works like this:
a = ["a", nil, "b"]
deleted = :none
deleted = a.delete_at(3) if a.index?(3) # => Deletion did not happen.
deleted # => :none # I can be sure that deletion did not happen.
a = ["a", nil, "b"]
deleted = :none
deleted = a.delete_at(1) if a.index?(1) # => Deleted `nil`.
deleted # => nil # I can be sure that an element `nil` was deleted.
Without checking the index, I cannot tell whether deletion happened:
a = ["a", nil, "b"]
deleted = :none
deleted = a.delete_at(3) # => Deletion did not happen.
deleted # => nil # I cannot tell whether an element `nil` was deleted or deletion did not happen.
a = ["a", nil, "b"]
deleted = :none
deleted = a.delete_at(1) if a.index?(1) # => Deleted `nil`.
deleted # => nil # I cannot tell whether an element `nil` was deleted or deletion did not happen.
=== Use case 2
I want to prepend with :foo
an element at position i
if there is such element.
With index?
, it works like this:
a = ["a", "b"]
a.insert(1, :foo) if a.index?(1)
# => ["a", :foo, "b"]
a = ["a", "b"]
a.insert(3, :foo) if a.index?(3)
# => ["a", "b"]
Without index?
, unwanted nil
will be inserted
a = ["a", "b"]
a.insert(1, :foo)
# => ["a", :foo, "b"] # This is okay.
a = ["a", "b"]
a.insert(3, :foo)
# => ["a", "b", nil, :foo] # Unwanted result
=end