0

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 ]

4 Answers 4

5

The other way round would be to use case-equal:

[1, 5, "dog", 6].reject &String.method(:===)
#⇒ [1, 5, 6]
Sign up to request clarification or add additional context in comments.

5 Comments

This is needlessly clever. reject {|s| String === s } is shorter, clearer, and (I'm guessing) more performant.
@Jordan, that it's shorter is a fact, subjectively, I too find it clearer, but I'm not sure about more "performant", as I've never been able to figure out what that means. Also the voting seems to cast doubt on it being "needlessly clever", and many here clearly have a need to post clever answers.
@Jordan: The advantage of point-free programming is that it avoids the need to artificially invent names for things that are not relevant to the solution at hand. As we all know, naming is hard. The flip side of that is: naming things elevates their importance. But what if they really are unimportant? Then, they should not have names.
I am not ignorant of that advantage. Neither, however, am I ignorant of the disadvantages. How you weigh that advantage against those disadvantages is subjective, but you should nevertheless weigh them.
4

try this:

arr.select! { |el| el.class != String }

or if you want only numbers:

arr.select! { |el| el.is_a? Numeric }

1 Comment

select is semantically incorrect, it’s worth it to use reject here.
2

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]

Comments

0

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 }

2 Comments

is_a? or === is preferable to calling .class on something manually.
Your first example doesn't work, returns an empty array []. This is because when checking the class of a regular number with class, it returns Fixnum. Whereas is_a? considers the ancestor classes too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.