What is the opposite of Array#reject in ruby?

RubyArrays

Ruby Problem Overview


Is seems that it might be keep_if.

If so, why isn't it called keep?

Ruby Solutions


Solution 1 - Ruby

  • The opposite of reject is select (returning a new array)
  • The opposite of reject! is select! (editing the array in place)
  • The opposite of keep_if is delete_if (editing the array in place)

Solution 2 - Ruby

I think it has to do with well thought-out semantics, and I'd argue that it is correct. Let's say you already have a set of things, "t1, t2, and t3"; if you reject a subset, you say "I reject t1 and t2". You don't mention t3, because it is not affected by your action (your rejection): the default is "keep". But if you are expressing what you intend to keep, and you just say "I keep t1 and t2", the status of t3 is called into question: after all, you already have t1 and t2, so what's the point of saying you're keeping them (they are already in the default state, "keep"), especially since you're implicitly also keeping t3. By using the syntax "keep_if", you are explicitly indicating that there is a condition (simple or compound) which will determine what is to be kept and what is to be discarded.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionB SevenView Question on Stackoverflow
Solution 1 - RubypguardiarioView Answer on Stackoverflow
Solution 2 - RubydavejView Answer on Stackoverflow