0
0
Rubyprogramming~5 mins

Each for iteration in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the each method do in Ruby?
The each method goes through every item in a collection like an array or hash, one by one, and runs the code inside the block for each item.
Click to reveal answer
beginner
How do you write a simple each loop to print all elements in an array [1, 2, 3]?
You write: <br>
 [1, 2, 3].each do |number| 
  puts number 
end 
This prints each number on its own line.
Click to reveal answer
beginner
What is the role of the block variable in an each loop?
The block variable (like |item|) temporarily holds the current element from the collection during each loop cycle, so you can use it inside the block.
Click to reveal answer
intermediate
Can each be used with hashes? How?
Yes! When used with a hash, each passes two block variables: the key and the value. For example: <br>
 {a: 1, b: 2}.each do |key, value| 
  puts "#{key}: #{value}" 
end 
Click to reveal answer
intermediate
What does the each method return after finishing the iteration?
The each method returns the original collection it was called on, unchanged.
Click to reveal answer
What does the each method do in Ruby?
AIterates over each element in a collection and runs a block of code
BDeletes elements from a collection
CSorts the elements in a collection
DCreates a new collection with modified elements
How do you access the current element inside an each block?
AUsing a method called <code>current</code>
BUsing a global variable
CYou cannot access it
DUsing a block variable like <code>|item|</code>
What does each return after running?
AThe last element
BThe original collection
CThe number of elements
DA new array with results
Which of these is a correct way to use each with a hash?
A{a: 1, b: 2}.each do |key, value| puts "#{key}: #{value}" end
B{a: 1, b: 2}.each do |item| puts item end
C{a: 1, b: 2}.each { puts key }
D{a: 1, b: 2}.each { |value| puts value }
What will this code print? <br>
 ["apple", "banana"].each do |fruit| puts fruit.upcase end 
Aapple banana
BError
CAPPLE BANANA (each on new line)
DNothing
Explain how the each method works in Ruby and how you use it with arrays.
Think about how you tell Ruby to do something for every item in a list.
You got /4 concepts.
    Describe how to use each with a hash and what block variables you need.
    Remember a hash has pairs, so you need two variables.
    You got /3 concepts.