Home > Mobile >  appending the outputs of an array method into another array
appending the outputs of an array method into another array

Time:12-28

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?

CodePudding user response:

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 }

CodePudding user response:

You can achieve this with each

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

  •  Tags:  
  • ruby
  • Related