-3

How can I remove elements from a given array of integers that are evenly divisible by 3? A new array should be returned and the original array should not be altered.

For example, if

array = [1,2,3,4,1,5,2,6,7,8,9,10,7,11,12,13,14,15]

the array

[1, 2, 4, 1, 5, 2, 7, 8, 10, 7, 11, 13, 14]

should be returned.

4
  • 4
    Please, show us what you tried.
    – mrzasa
    Jan 14, 2019 at 15:19
  • Possible duplicate of How to remove all elements that satisfy a condition in array in Ruby?
    – iGian
    Jan 14, 2019 at 15:35
  • 1
    Sharp, one problem with your statement of the question was your choice of example. By making the array [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] readers might conclude you wanted to remove every third element rather than every element that equals a multiple of 3. Also, always make it clear whether you want to return a new object and leave the original object unchanged, or modify (mutate) the original object. Jan 14, 2019 at 20:54
  • Readers: if you believe the edited question is now clear, please consider voting to reopen. Note that the answer given by the OP is consistent with the current statement of the question. Jan 15, 2019 at 0:32

1 Answer 1

7

Just found it:

array.reject{|a| a % 3 == 0}
2
  • 1
    This works. You might also want to look into the reject! method, which modifies the array variable.
    – AJFaraday
    Jan 14, 2019 at 15:30
  • It does not modify the array variable. It modifies the array. That is completely different. A thing and a name of a thing are two different things. Jan 16, 2019 at 18:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.