Question: How to check if an element in an array exists in another array

Question

How to check if an element in an array exists in another array

Answers 3
Added at 2016-12-03 01:12
Tags
Question

I have two different arrays of strings, array1 and array2, in which I want to find out if the elements in array1 also exist in array2 without modifying the elements in array1, but the values in array1 include the extra characters including and after the colon :.

array1 = ["unit 1 : Unit 1","unit 2 : Unit 2","unit 3 : Unit 3","test : Test", "system1"]
array2 = ["unit 1","unit 2","unit 3","test"]

I tried using include? but it doesn't work.

array1.each do |element|
    #see if element exists in array 2
    if array2.include? element
         #print the name of that element
         puts element
    end
end

How would I approach this?

Answers to

How to check if an element in an array exists in another array

nr: #1 dodano: 2016-12-03 01:12

Fixing your approach, you could split the element with space+:+space and get the first chunk for the check. Instead of if array2.include? element use

if array2.include? element.split(' : ').first

See the Ruby demo

nr: #2 dodano: 2016-12-03 01:12
# Gather the prefixes from array1, without modifying array1:
array1_prefixes = array1.map { |s| s.split(" : ").first }

# Figure out which elements array1 and array2 have in common
common_elements = array1_prefixes & array2
# => ["unit 1", "unit 2", "unit 3", "test"]

This solution relies on the Array#& operator, which performs set intersection.

nr: #3 dodano: 2016-12-03 11:12

I think the most readable method to use here might be startwith?, but if you know a key cannot be a substring of another key.

To see if all keys are in place:

array2.all? do |item|
  array1.any?{|keyval| keyval.startwith? item }
end
Source Show
◀ Wstecz