-1

I have an array a = ["1","2","3","6","7"] and another array b = ["2","4","7"]. I want to check if any content of b exists in a or not.

0

3 Answers 3

2

You can do

a = ["1","2","3","6","7"]
b = ["2","4","7"]
b.any? { |e| a.include?(e) }
Sign up to request clarification or add additional context in comments.

1 Comment

See my comment at G.B.'s answer
2

that is so simple:

(a & b).blank?

actually what does it do is, it takes intersection of two array and returns the result then check if the result is blank/empty.

1 Comment

If the user seems to ask a simple question, he probably is not very experienced in Ruby. Therefore some explanation of your answer would be appropriate.
1

Use & operator of Ruby, it will return an array with intersection values of two arrays, below is an example.

pry(main)> a = ["1","2","3","6","7"]
=> ["1", "2", "3", "6", "7"]
pry(main)> b = ["2","4","7"]
=> ["2", "4", "7"]
pry(main)> a & b
=> ["2", "7"]
pry(main)> (a & b).empty?
=> false

In Rails, you can also use blank?

pry(main)> (a & b).blank?
=> false

Hope the above example helps

2 Comments

I guess empty? method would be better here since it comes from Ruby std library (blank? comes from activesupport), so it would be more general solution.
Yes @MarekLipka, I agree with you, empty can also be used, I will edit the answer. Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.