I wrote this code to make a hash where the keys are categories (fruit or veg) and the values an array of items in that category.
food = ["fruit:orange", "fruit:apple", "fruit:cherry", "veg:pea", "veg:parsley"]
food.each_with_object(Hash.new([])) do |food_item, hash|
category, value = food_item.split(":")
hash[category] = hash[category].push(value)
end
This is what I get:
# =>
{
"fruit" => ["orange", "apple", "cherry", "pea", "parsley"],
"veg" => ["orange", "apple", "cherry", "pea", "parsley"]
}
But I expected this:
{
"fruit"=> ["orange", "apple", "cherry"],
"veg" => ["pea", "parsley"]
}
The first iteration should produce { fruit: ["orange"] }
, the second { fruit: ["orange", "apple"] }
etc... the fourth iteration should create the veg key, and continue on. How do the veggies end up pushed to the fruits array and vice-versa?