Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
array exercises
# Two alternative approaches for https://gist.github.com/peeyush14goyal/506689c0227ff7d7a6071c30f1166a27
todos = [
["Send invoice", "money"],
["Clean room", "organize"],
["Pay rent", "money"],
["Arrange books", "organize"],
["Pay taxes", "money"],
["Buy groceries", "food"]
]
categories = todos.map {|todo| todo[1] }.uniq
# A functional approach
categories.each do |category|
puts "#{category}:"
todo_names =
todos.filter {|todo| todo[1] == category}.
map {|todo| " #{todo[0]}"}.
join("\n")
puts todo_names
end
# A more imperative approach
categories.each do |category|
puts "#{category}:"
todos_for_this_category = todos.filter {|todo| todo[1] == category}
todos_for_this_category.each do |todo|
puts " #{todo[0]}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment