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.
Asked
Active
Viewed 72 times
3 Answers
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.

Abdul Baig
- 3,683
- 3
- 21
- 48
-
2If 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. – Jan Doggen Oct 31 '14 at 10:47
2
You can do
a = ["1","2","3","6","7"]
b = ["2","4","7"]
b.any? { |e| a.include?(e) }

Arup Rakshit
- 116,827
- 30
- 260
- 317
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

Rajdeep Singh
- 17,621
- 6
- 53
- 78
-
2I 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. – Marek Lipka Oct 31 '14 at 10:24
-
Yes @MarekLipka, I agree with you, `empty` can also be used, I will edit the answer. Thanks – Rajdeep Singh Oct 31 '14 at 10:25