0

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.

1
  • 1
    Please show what have you tried so far. Commented Nov 17, 2014 at 10:12

3 Answers 3

4

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

3 Comments

Thanks a lot, I already tried this. But unfortunately I forgot to do a "chomp" at the array. Because I filled the array from a file. First I thought "result - exclude" don't work for me, but you made me check my code again. I know it is a terrible newbie mistake, but I wasn't able to find this mistake for hours!
Added code to iterate and remove items. I hope you have a reason to make it this way.
The added code works also fine. I will use your first proposal. But I learned a lot Ruby Stuff today. Thank you, Yossi
3

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.

Comments

1

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')}

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.