Skip to content

Instantly share code, notes, and snippets.

@Whatapalaver
Last active July 19, 2018 11:04
Show Gist options
  • Save Whatapalaver/d497474cf431e25df521fcbc20c8280c to your computer and use it in GitHub Desktop.
Save Whatapalaver/d497474cf431e25df521fcbc20c8280c to your computer and use it in GitHub Desktop.
Hash woes

Here's an example of producing output of an array of hashes, grouped by one of the keys

In this case students is an array of hashes showing student names and the cohort they are enrolled in
The output summarises by cohort and lists the relevant enrolled student names

def print_by_category(students)
  # print the students grouped by cohort
  cohort_array = []
    students.each do |hash|
      cohort_array.push(hash[:cohort]).uniq!
    end

    cohort_array.each do |cohort|
      puts cohort
      students.each_with_index do |student, index|
        if student[:cohort] == cohort
          puts "#{index + 1}. #{student[:name]} (#{student[:cohort]} cohort)".center(50)
        end
      end
    end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment