Jack Kelly Jack Kelly - 2 months ago 10
Ruby Question

How do i filter my array of hashes to output only the hashes I would like?

So far I have figured out how to sort my hashes by a specification of cohort:

bycohort = students.sort_by { |v| v[:cohort] }

This method allows me to sort my hashes in my input method.Once printed with the print_with_index method, it outputs this to the screen:

1. Penny (january cohort)
2. Nicole (may cohort)
3. Ali (may cohort)
4. Jack (november cohort)
5. John (november cohort)
6. Olu (november cohort)
7. Henry (september cohort)
8. Olivia (september cohort)

I use a separate method for printing the array of hashes:

def print_with_index(students)
students.each_with_index do |students, index|
index_plus_one = index + 1
puts "#{index_plus_one}. #{students[:name]} (#{students[:cohort]} cohort)"

I would like to remove all hashes other that those with a November cohort. How do I do this as I am stumped.

students.select! { |student| student[:cohort] == :november }

if student[:cohort] is a symbol. Otherwise, if that is a string

students.select! { |student| student[:cohort] == 'november' }

Or, this works for both

students.select! { |student| student[:cohort].to_sym == :november }