|
You can actually do much much with a for loop than counting a variable.
Let's take this example:
for dinner in ['fishchips','porkchops','soup','pizza']
puts dinner.calories
end
Yep..you probably guessed this one..If you're worried about your general state of health and need to keep track of your caloric intake..well..learn Ruby and make yourself a nifty little program based on the code above.
The [ fishchips, porkchops, soup, pizza ] is an array, what the for loop does is iterate over the array and display calories for each entry in the array.
Another way of "looping" or iterating over something is using the .each method.
So, for example if you'd have a structure like this:
toppings = ['mushrooms','salami','pineapple','anchovies']
you could do this:
toppings.each do |topping|
puts "#{topping} is available for your pizza"
end
As the .each method iterates through the collection of toppings, each topping is saved in the variable topping and used for displaying the corresponding message on screen.
|