0

how can i compare if an array of strings contains a smaller array of strings in Ruby?

e.g.

a=["1","2","3","4","5"]
b=["2","3"]

now i want to check if a contains b and get true/false

Thanks.

3
  • you can check by (a & b) == b, it will return boolean value true / false Commented Aug 10, 2018 at 10:33
  • @GaganGami nope, this is not correct; & squeezes duplicates resulting in weird [1, 1] & [1, 1] == [1, 1] #⇒ false because surprisingly [1, 1] & [1, 1] == [1]. Commented Aug 10, 2018 at 10:51
  • @mudasobwa : noted, thanks Commented Aug 10, 2018 at 12:39

1 Answer 1

0

The most common approach would be to

(b - a).empty?

It has issues with unique elements, though. To detect whether a includes all elements from b, one should:

a_copy = a.dup
b.all? { |e| a_copy.delete e }
# or
b.all?(&a_copy.method(:delete))
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I solved it with b.all? { |x| a.include(x) }
@EnginTopuzoglu once again, it won’t work if arrays might contain duplicates.
I see, thanks, they dont contain duplicates but they might, so i changed it to your code, still working

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.