Bitwise
Bitwise

Reputation: 8461

Delete Strings from an array in Ruby

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

Answers (4)

davidhu
davidhu

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

Jordan Running
Jordan Running

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

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

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

[1, 5, "dog", 6].reject &String.method(:===)
#⇒ [1, 5, 6]

Upvotes: 5

Bartłomiej Gładys
Bartłomiej Gładys

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

Related Questions