I think what you’re looking for in your most recent example is Hash#fetch:
def generate_item_by_id(id, mods)
quantity = 1
cold_res = mods.fetch "cold_res", default: 0
fire_res = mods.fetch "fire_res", default: 0
lightning_res = mods.fetch "lightning_res", default: 0
{id, quantity, cold_res, fire_res, lightning_res}
end
mods_to_roll = {"cold_res", "fire_res", "lightning_res"}
mods = Hash(String, Int32).new
3.times do
mods[mods_to_roll[rand(mods_to_roll.size)]] = 20
end
pp generate_item_by_id(5, mods)
https://play.crystal-lang.org/#/r/7zxx
I suspect that this could be more easily solved with a struct, though. How do you get your hash in the first place?