将数组方法的输出附加到另一个数组中


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

我创建了一个数组(array3),它包含了相应的元素,我想添加array3中满足条件的元素,但在执行代码后,我得到一个空白数组,如"[[], [], []]"我如何解决这个问题?

find_index不遍历索引。它遍历值并返回匹配值的第一个索引。听起来像是要遍历每个元素,记录所有符合某些条件的索引。

为此,您可以使用each_with_index

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

或者您可以使用each_index并过滤结果。

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

或,用each_with_index过滤,

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

在Ruby 2.7或更新版本上,你可以用filter_map来缩短它。

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

您可以使用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

相关内容