the hash I have is the following:
aoh=[
{ "name": "Vesper",
"glass": "martini",
"category": "Before Dinner Cocktail",
"ingredients": [
{ "unit": "cl",
"amount": 6,
"ingredient": "Gin" },
{ "unit": "cl",
"amount": 1.5,
"ingredient": "Vodka" },
{ "unit": "cl",
"amount": 0.75,
"ingredient": "Lillet Blonde" }
],
"garnish": "Lemon twist",
"preparation": "Shake and strain into a chilled cocktail glass." },
{ "name": "Bacardi",
"glass": "martini",
"category": "Before Dinner Cocktail",
"ingredients": [
{ "unit": "cl",
"amount": 4.5,
"ingredient": "White rum",
"label": "Bacardi White Rum" },
{ "unit": "cl",
"amount": 2,
"ingredient": "Lime juice" },
{ "unit": "cl",
"amount": 1,
"ingredient": "Syrup",
"label": "Grenadine" }
],
"preparation": "Shake with ice cubes. Strain into chilled cocktail glass." }]
How can I iterate through this to get JUST the ingredient (without returning name,glass,category,etc.)? I also need the same iteration for amount but I assume that will look just like the iteration for ingredient. Sorry for the dumb question, I'm new to ruby and have attempted this for hours now.
You have an array of two elements in your example. Those two elements are hashes with key/value pairs. You can loop through the array with the
#eachmethod and access the values that the:"ingredients"keys store like this:The
:ingredientskeys each store another array of hashes. An example hash is:You can then access the value under the
:ingredientkey by doinghash[:ingredient]. The final result looks something like this:This currently only iterates through the arrays and hashes. If you want to also print the result you can do this:
If you want to get a modified array, you can use
#map(or#flat_map). You can also get the amount with the value like this: