OneBite.Dev - Coding blog in a bite size

find the common elements in two arrays in Ruby

Code snippet on how to find the common elements in two arrays in Ruby

arr1 = [1, 2, 3, 4, 5, 6]
arr2 = [3, 5, 7, 8]

common_elements = arr1 & arr2

puts "Common elements in two arrays: #{common_elements.join(', ')}"

This code will find the common elements in two arrays and print out the results. Firstly, two arrays (arr1 and arr2) are created. The ampersand operator (&) is then used to compare both arrays, which will give an array with all the common elements from both arr1 and arr2. Lastly, the “puts” command will print out the common elements, which are joined together by a comma so they are all displayed in one line.

ruby