Bent Blue
Bent Blue

Reputation: 166

Delete a string in an array when it exist in another array

In a ruby-script I have two arrays

exclude = ['bgb400', 'pip900', 'rtr222']
result = ['pda600', 'xda700', 'wdw300', 'bgb400', 'ztz800', 'lkl100']

I want to iterate over the result array and remove any string that exists in the exclude array. In the end the string 'bgb400' should be removed from the result array.

Upvotes: 0

Views: 92

Answers (3)

Darkmouse
Darkmouse

Reputation: 1939

It sounds like Array#delete_if method is best for this task.

exclude = ['bgb400', 'pip900', 'rtr222']
result = ['pda600', 'xda700', 'wdw300', 'bgb400', 'ztz800', 'lkl100']

In order to remove elements in the reuslt array that are included in the excude array try this

result.delete_if{|r|exclude.include?('r')}

Upvotes: 1

Yossi
Yossi

Reputation: 12100

Use operator -

irb(main):004:0> result - exclude
=> ["pda600", "xda700", "wdw300", "ztz800", "lkl100"]

If you really need to modify your result array you can use reject!. However if it is the case, you better review your code.

result.reject! {|s| exclude.include? s}

Upvotes: 4

Abdul Baig
Abdul Baig

Reputation: 3721

simply do:

new_result = result - exclude
=> ["pda600", "xda700", "wdw300", "ztz800", "lkl100"]

actually what it does is check for matching entries in both arrays and produce the result excluding the matching entries.

Upvotes: 3

Related Questions