Said Kaldybaev
Said Kaldybaev

Reputation: 10002

best way to remove strings in array with Ruby

lets say i've got this array:

array = ["str1", "str2", "str3", "str4", "str5", "str6", "str7", "str8"]

what i'm doing:

array.delete_if {|i| i == "str1" || i == "str3" || i == "str5"}

i got:

["str2", "str4", "str6", "str7", "str8"]

are there any better approach in ruby to do this ?

Upvotes: 17

Views: 23514

Answers (2)

DDD
DDD

Reputation: 489

array.reject{|e| e=~ /str[135]/}

Upvotes: 2

Alex D
Alex D

Reputation: 30495

You could do this:

array - %w{str1 str2 str3}

Note that this returns a new array with "str1", "str2", and "str3" removed, rather than modifiying array directly (as delete_if does). You can reassign the new array to array concisely like this:

array -= %w{str1 str2 str3}

Upvotes: 40

Related Questions