Feature #12360

More useful return values from bang methods

Added by trans (Thomas Sawyer) over 2 years ago. Updated over 2 years ago.

Target version:


It would be nice if bang methods returned results that where of some additional use. Presently most just return the effected receiver.

For example, currently Array#reject! works as follows:

a = [1,2,3,4]
a.reject!{ |x| x % 2 == 0 }
=> [2,4]
=> [2,4]

So the return value of #reject! is useless b/c it is just the same as a (in this example). So why not return what was rejected instead:

a = [1,2,3,4]
a.reject!{ |x| x % 2 == 0 }
=> [1,3]
=> [2,4]

Now we have useful additional information -- we know exactly what got rejected. To do the same thing presently we would have to fully duplicate the original array and then take the difference -- two extra steps.

The downside is that the method would consume a little more memory and probably slow the method's execution a little too. But I tend to side with functionality when I use Ruby.


Updated by shyouhei (Shyouhei Urabe) over 2 years ago

reject! returns nil in case nothing was rejected at all. This is useful when a programmer wants to know if actual rejection happened or not, by using single if statement.
Returning rejected elements can be handy on some scenarios, though. Maybe a separate method?

Updated by nobu (Nobuyoshi Nakada) over 2 years ago

I think this proposal is to change the return value if actual rejection happened, but not the case nothing was rejected, and the result doesn't need to be self to know if it happened or not.

A drawback is a cost to create an array always even if it is not used.

Updated by dsferreira (Daniel Ferreira) over 2 years ago

The principle of least surprise puts my mind expecting as a result the updated array.
A method to get both sides of the equation would make sense for me.
Something like:

# Array#group

[1,2,3,4].group { |i| (-1)**i > 0 }
# => [[2,4], [1,3]]

Updated by matz (Yukihiro Matsumoto) over 2 years ago

  • Status changed from Open to Rejected

Rejected for several reasons:

  • compatibility: the change will break many existing programs relying on the current behavior.
  • it decreases the performance of bang methods. since the primary reason for using bang method is efficiency, it is not acceptable.
  • the reason behind the current return value is to prevent method chaining of bang methods. since bang methods modifies the receivers, chaining them can easily confuse programmers.


Also available in: Atom PDF