0

I would like to compare two arrays and return the first value of array 1 that matches an item from array two. Here is what I have so far:

def find_the_color(array_1)
  array_2 = ["red", "yellow", "blue"]
  sample.find do |x|
    x=="red"||x=="yellow"||x=="blue"
  end
end

I would like to do this using the array instead of separating it into 3 conditional statements. Is there a way?

3 Answers 3

1

Simply do this

 array_1.find { |x| array_2.include?(x) }
Sign up to request clarification or add additional context in comments.

Comments

1
array_1 = [ 'green', 'yellow' ]
array_2 = ["red", "yellow", "blue"]
( array_1 & array_2 ).first

Comments

1

If performance is important, first convert array_2 to a Set:

array_1 = %w{ green yellow orange purple mauve black blue }
array_2 = %w{ pink red mauve white brown }

require 'set'

set_2 = array_2.to_set
array_1.find { |e| set_2.include? e }
  #=> "mauve"

By converting array_2 to a set at the onset, set_2.include? e can be executed quickly (similar to looking up the value of a hash key). By contrast, with Array#include?, array_2 must be enumerated for each element of array_1 until a match is found.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.