Introduction
You use 'each' to repeat a set of actions for every item in a list or collection. It helps you handle many items one by one easily.
collection.each do |item| # code to run for each item end
numbers = [1, 2, 3] numbers.each do |num| puts num end
fruits = ['apple', 'banana', 'cherry'] fruits.each { |fruit| puts fruit.upcase }
hash = {a: 1, b: 2}
hash.each do |key, value|
puts "#{key} is #{value}"
endcolors = ['red', 'green', 'blue'] colors.each do |color| puts "I like #{color}" end
each method do in Ruby when used with an array?eacheach method is used to loop over every element in a collection like an array.each runs once for each element, allowing actions on each item.each repeats actions per item [OK]numbers using each in Ruby?each syntaxeach method is called on the array, followed by a block with a parameter inside pipes.|num| and a valid block body puts num.fruits = ['apple', 'banana', 'cherry'] fruits.each do |fruit| puts fruit.upcase end
puts fruit.upcase.puts prints each string on a new line, so each fruit name appears uppercase on its own line.numbers = [1, 2, 3] numbers.each do num puts num * 2 end
|num| when using do...end.do num instead of do |num|, causing a syntax error.scores = { alice: 10, bob: 15, carol: 12 }, how can you use each to print each name and score in the format Name: Score?each, two block variables receive the key and value respectively.|name, score| and prints with #{name.capitalize}: #{score}.Pass the test and this pattern moves unknown