-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.

sawa
  • 165,429
  • 45
  • 277
  • 381
Emu
  • 5,763
  • 3
  • 31
  • 51

3 Answers3

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
  • 2
    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. – 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
  • 2
    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. – 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