Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

appending the outputs of an array method into another array

array3 =['Maths', 'Programming', 'Physics'], ['Maths', 'Intro to comp. science', 'Programming'], ['English', 'Intro to comp. science', 'Physics']
course = 'Programming'    
index = []
array3.find_index do |i|
  if array3.include?(course) == true
  index << i
  end
end

i created an array (array3) that contains the respective elements and i want to add the elements of array3 which hold the condition true but after executing the code i get a blank array like "[[], [], []]"
how can i fix this issue?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

find_index does not iterate over indices. It iterates over values and returns the first index of the value that matches. It sounds like you want to iterate over every element, making note of all of the indices that match some condition.

To that end, you can use each_with_index.

index = []
array3.each_with_index do |courses, i|
  if courses.include?(course) == true
  index << i
  end
end

or you can use each_index and filter the results.

index = array3.each_index.select { |index| array3[index].include? course }

or, filtering with each_with_index,

index = array3.each_with_index
        .select { |list, _| list.include? course }
        .map(&:last)

on Ruby 2.7 or newer, you can shorten this with filter_map.

index = array3.each_with_index
              .filter_map { |obj, index| index if obj.include? course }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading