DEV Community

sam-a-code
sam-a-code

Posted on

My Favorite Methods (max_by, find_by, and sum)

We're just about done with Phase 3 of our program, so I'm back with another blog post! Today I'm going to highlight some of my favorite methods in Ruby.

For the examples below, let's say that we have a plant_store with plants and customers that we'll want to look through, sort, and find.

max_by

Say we wanted to find the customer who had purchased the most number of plants from the plant_store.

def self.most_plant_purchases 
    self.all.max_by {|customer| customer.plants.count }
 end
Enter fullscreen mode Exit fullscreen mode

In the above class method, the self is referring to PlantStore.
When we call this method on the PlantStore class, we iterate through every instance of customer. We do plants.count on each customer to get the total number of plants they've purchased. Once this method has gone through each customer, it will return the customer with the highest number of plants (lucky customer!).

find_by

What if our customer is looking for a specific plant? We can search for what they're looking for using find_by!

def find_plant(plant_name)
    self.plants.find_by(plant_name: plant_name)
end
Enter fullscreen mode Exit fullscreen mode

This instance method is called on the PlantStore class. We pass in one argument of a plant name and the method searches for any plant_name that matches our argument in the plant_name: attribute. It will return the first instance of a plant that has a name that matches plant_name.

sum

Finally, what if we wanted to find out how much a customer had spent on plants at that plant_store?

  def total_plant_cost
    self.plants.sum {|plant| plant.price}
  end
Enter fullscreen mode Exit fullscreen mode

This instance method is called on the Customer class. It calculates the sum of all of a customer's plants by adding up the values of the price attribute for each plant that is associated with that customer.

Thanks for reading!

Hopefully these methods are helpful references for your own projects! I tried to keep it simple so this would be an easy reference :)

Top comments (0)