Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way to remove strings in array with Ruby

Tags:

arrays

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 ?

like image 585
Said Kaldybaev Avatar asked Sep 14 '12 19:09

Said Kaldybaev


People also ask

How do you remove something from an array in Ruby?

Array#delete() : delete() is a Array class method which returns the array after deleting the mentioned elements. It can also delete a particular element in the array. Syntax: Array. delete() Parameter: obj - specific element to delete Return: last deleted values from the array.


1 Answers

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}
like image 133
Alex D Avatar answered Sep 18 '22 16:09

Alex D