Ruby 2.6.5
Have a method to interact array of hashes and filter them. User can put array of students and as many filters as he wants. If I use one filter, everything is going fine. But if I put second filter, the program is hangs in irb console and nothing is going on. Memory limit exceeded. What am I doing wrong?
def filter(students, *filters)
return students if filters.empty?
result = []
filters.each do |filter|
students.each { |student| result << student if filter.call(student) }
students = result
end
result
end
students = [
{ name: 'Thomas Edison', gpa: 3.45 },
{ name: 'Grace Hopper', gpa: 3.99 },
{ name: 'Leonardo DaVinci', gpa: 2.78 }
]
filter_1 = ->(record) { record[:gpa] > 3.0 }
filter_2 = ->(record) { record[:gpa] < 3.9 }
If I will call the method only with filter_1 or filter_2 (filter(students, filter_2)
), everything is going fine, but when I put there one more argument (filter(students, filter_1, filter_2)
), the programs is hanging.
What I did already
If I will delete only one string (students = result
) code will work. And fast return the result:
filter(students, honor_roll, filter_2)
=> [{:name=>"Thomas Edison", :gpa=>3.45}, {:name=>"Grace Hopper", :gpa=>3.99}, {:name=>"Thomas Edison", :gpa=>3.45}, {:name=>"Leonardo DaVinci", :gpa=>2.78}]
But I need exactly implement filters one by one. I tried to modificate arrays of results after implementing each iteration, but there is the same problem. Also I tried to not use students
array:
def filter(students, *filters)
# Write your code here
return students if filters.empty?
result = []
filters.each_with_index do |filter, index|
array = index.zero? ? students : result
array.each { |student| result << student if filter.call(student) }
end
result
end
But result is the same.
How can I fix this? Thank you so much!