Reputation: 8461
Let's say I have an Array that looks like this:
arr = [ 1, 5, "dog", 6 ]
How can I delete the String so that my output will look like this:
[ 1, 5, 6 ]
Upvotes: 0
Views: 466
Reputation: 10434
You can also go the opposite way and use reject!
. It removes all the elements that matches the condition you set.
arr.reject! { |el| !el.is_a? Numeric }
This is functionally the same as
arr.select! { |el| el.is_a? Numeric }
Upvotes: 0
Reputation: 106027
This is a good opportunity to use Enumerable#grep
or Enumerable#grep_v
:
[ 1, 5, "dog", 6 ].grep(Numeric)
# => [1, 5, 6]
[ 1, 5, "dog", 6 ].grep_v(String)
# => [1, 5, 6]
Upvotes: 2
Reputation: 121000
The other way round would be to use case-equal:
[1, 5, "dog", 6].reject &String.method(:===)
#⇒ [1, 5, 6]
Upvotes: 5
Reputation: 4615
try this:
arr.select! { |el| el.class != String }
or if you want only numbers:
arr.select! { |el| el.is_a? Numeric }
Upvotes: 4