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.
My code is:
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
CodePudding user response:
You're close, but:
- You don't need to do anything with your order to make it an index.
orders.each
will just returnorders
when it's done.- You need to handle
DISHES_CALORIES[element]
returningnil
.
You can pass a block to #sum
.
def calories_counter(orders)
orders.sum { |order| CALORIES_COUNTER[order] || 0 }
end
CodePudding user response:
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