Skip to content

Instantly share code, notes, and snippets.

@jasim
Created January 16, 2021 10:41
Show Gist options
  • Save jasim/a209a0978d625cf5cbaedf86e21ab1f8 to your computer and use it in GitHub Desktop.
Save jasim/a209a0978d625cf5cbaedf86e21ab1f8 to your computer and use it in GitHub Desktop.
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