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.
3 Answers
You can do
a = ["1","2","3","6","7"]
b = ["2","4","7"]
b.any? { |e| a.include?(e) }
1 Comment
Jan Doggen
See my comment at G.B.'s answer
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
Jan Doggen
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.
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
Marek Lipka
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.Rajdeep Singh
Yes @MarekLipka, I agree with you,
empty can also be used, I will edit the answer. Thanks