Ruan Odendaal
Ruan Odendaal

Reputation: 83

Removing values in an array that contain a specific number

I'm trying to remove any value that contains a 5 so in this case the 5, 15, 25 and 53 should all be removed.

Have tried the below and played around in irb but can't seem to get it to work

n = [1, 2, 3, 4, 5, 6, 7, 8, 9, 15, 25, 53]
n.delete_if { |a| a =~ /5*/ }

Upvotes: 2

Views: 62

Answers (3)

Andrey Deineko
Andrey Deineko

Reputation: 52357

You're looking for an Array#reject:

n.reject { |number| number.to_s =~ /5/ }
#=> [1, 2, 3, 4, 6, 7, 8, 9]

Upvotes: 4

guitarman
guitarman

Reputation: 3310

With Array#delete_if it works as well:

n = [1, 2, 3, 4, 5, 6, 7, 8, 9, 15, 25, 53]
n.delete_if { |a| a.to_s =~ /5/ }
# => [1, 2, 3, 4, 6, 7, 8, 9]

Upvotes: 2

Stefan
Stefan

Reputation: 114178

Ruby 2.4 comes with Integer#digits:

n = [1, 2, 3, 4, 5, 6, 7, 8, 9, 15, 25, 53]
n.reject { |i| i.digits.include? 5 }
#=> [1, 2, 3, 4, 6, 7, 8, 9]

Upvotes: 4

Related Questions