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 ]
The other way round would be to use case-equal:
[1, 5, "dog", 6].reject &String.method(:===)
#⇒ [1, 5, 6]
reject {|s| String === s } is shorter, clearer, and (I'm guessing) more performant.try this:
arr.select! { |el| el.class != String }
or if you want only numbers:
arr.select! { |el| el.is_a? Numeric }
select is semantically incorrect, it’s worth it to use reject here.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]
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 }
is_a? or === is preferable to calling .class on something manually.[]. This is because when checking the class of a regular number with class, it returns Fixnum. Whereas is_a? considers the ancestor classes too.