Skip to content

Instantly share code, notes, and snippets.

@dsasse07
Last active September 3, 2021 03:17
Show Gist options
  • Save dsasse07/e9d69f69e2c9f63ccc27b8fd3205692e to your computer and use it in GitHub Desktop.
Save dsasse07/e9d69f69e2c9f63ccc27b8fd3205692e to your computer and use it in GitHub Desktop.
aggregate methods refactored using .send
def self.count_vhs_rentals_by(attribute)
Rental.all.each_with_object({}) do |rental, vhs_hash|
vhs_hash[rental.send(“#{attribute}”)].nil? ? vhs_hash[rental.“#{attribute}”] = 1 : vhs_hash[rental.“#{attribute}”] += 1
end
end
Vhs.count_vhs_rentals_by(“vhs”) #=>
#{<Vhs:0x00007f8d5e2bf0f0 id: 17, serial_number: "MAX-luqovgdk8e7tl", movie_id: 9 => 1,
#<Vhs:0x00007f8d4f81a4a0 id: 29, serial_number: "BABA-t6k24krzqclts", movie_id: 13 =>2,
#<Vhs:0x00007f8d4f854538 id: 11, serial_number: "BABA-begvxe7ai0rc6", movie_id: 13 =>3}
Vhs.count_vhs_rentals_by(“client”) #=>
#{#<Client:0x00007f8d5e2ae6d8 id: 4, name: "Hank Jennings" =>1}
#<Client:0x00007f8d5e2be3a8 id: 7, name: "Lisa Wilkes" =>2}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment