ruby - DRYing up these helper methods -
i've got 3 methods this:
def total_fat total = 0 meal_foods = current_user.meal_foods meal_foods.each |food| total += food.fat end return total end
one fat, carbs, , protein.
i'd dry up.
i've tried method , didn't seem work passing in 'macro' string.
def total_of(macro) total = 0 meal_foods = current_user.meal_foods meal_foods.each |food| total += food.macro end return total end
how this?
def total_of(marcro) current_user.meal_foods.map(&marcro).inject(:+) end
this takes array(-like) collection of meal_foods
, maps array of marcro
value of meal_foods
, , injects "+" between each of numbers. make sure pass argument symbol, e.g. total_of(:fat)
.
Comments
Post a Comment