Home > Net >  RUBY - Hash and Array // Explanation of a method use
RUBY - Hash and Array // Explanation of a method use

Time:10-31

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:

  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

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
  • Related