Ruby: how to remove items from array A if it's not in array B?

前端 未结 2 1139
离开以前
离开以前 2021-01-23 14:06

I have prepare these two arrays:

list_of_students = Student.where(\'class = ?\', param[:given_class])
list_of_teachers = Teacher.where(...)

2条回答
  •  情深已故
    2021-01-23 14:13

    You can try something like

    a = [1,2,3]
    b = [1,4,5]
    
    pry(main)> a.delete_if {|a1| !b.include? a1}
    => [1]
    

    it checks each value in a is in b or not. If not it deletes the value from a and gives you a array finally.

    This is an example. You can use this accordingly

提交回复
热议问题