17

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 ?

2 Answers 2

40

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}
Sign up to request clarification or add additional context in comments.

3 Comments

array -= %w[ ... ] would do an in-place reassignment but would not alter any references to the original array.
Good idea; I added it to the original answer.
just so people know, %w{word word2} does not accept variables containing strings. I didn't know and it will not remove the string from the array. I used array -= [variable_containing_string] to make it work
2
array.reject{|e| e=~ /str[135]/}

Comments

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.