Esteban
Esteban

Reputation: 3

RUBY - Hash and Array // Explanation of a method use

I have a hash, where each key has a value (an integer). What I want to do is to create a method, where I write as an argument an array, this array will have written inside the name of the different keys.

So once I give the array to the method, it will sum all the values from each element. But I am not sure how to go through my array, and put all the elements inside the hash, and then sum it, and get the total value.

Here is my code:

DISHES_CALORIES = {
  "Hamburger" => 250,
  "Cheese Burger" => 300,
  "Veggie Burger" => 540,
  "Vegan Burger" => 350,
  "Sweet Potatoes" => 230,
  "Salad" => 15,
  "Iced Tea" => 70,
  "Lemonade" => 90
}

def poor_calories_counter(burger, side, beverage)
  DISHES_CALORIES[burger] + DISHES_CALORIES[side] + DISHES_CALORIES[beverage]
end

def calories_counter(orders)
  # TODO: return number of calories for a less constrained order
  sum = 0
  orders.each { |element| sum = sum + DISHES_CALORIES[":#{element}"] }
end

Upvotes: 0

Views: 489

Answers (3)

steenslag
steenslag

Reputation: 80065

You could allow for multiple menu items like this:

choices = ["Hamburger","Salad","Lemonade"]

p DISHES_CALORIES.values_at(*choices).sum # => 355

Upvotes: 0

Ritesh Choudhary
Ritesh Choudhary

Reputation: 782

You can also use default value of hash for calculating calories in all places without errors

DISHES_CALORIES.default = 0

def calories_counter(orders)
  orders.sum { |element| DISHES_CALORIES[element] }
end

Upvotes: 0

Chris
Chris

Reputation: 36440

You're close, but:

  1. You don't need to do anything with your order to make it an index.
  2. orders.each will just return orders when it's done.
  3. You need to handle DISHES_CALORIES[element] returning nil.

You can pass a block to #sum.

def calories_counter(orders)
  orders.sum { |order| CALORIES_COUNTER[order] || 0 }
end

Upvotes: 2

Related Questions