Each block parameters


Collapse Content

Blocks can also take in parameters from the method they are passed to. In Ruby, the most common way to loop through a collection is to pass a block to the each method:

(1..3).each do |index|
  puts "number #{index}"
end

This will output:

number 1
number 2
number 3

each goes through the collection of items and passes each item to the block. This is the equivalent to a for-loop, but considered more rubyish.

each is used by the other ruby collections, such as arrays:

array.each do |element|
  puts "#{element} is part of the array"
end

...and hashes, where you can use two variables to iterate through keys and values:

hash.each do |key, value|
  puts "#{key} is #{value}"
end

While each just goes through each item in a collection, Ruby also includes other methods for doing something with those items. map uses the block you pass it to map all the items to new values. For example, this code will return an array where each number has been doubled:

 [1, 2, 3, 4].map do |n| 
   n*2
 end
 #=> [2, 4, 6, 8]

Blocks may seem confusing at first, but they allow for concise and powerful code.

Next: Learn about objects, classes and more in Ruby and Rails!

Challenge

Given ar, an array of numbers, return an array containing the squares of all those numbers.

Guideline: Use map to map the numbers to their squares.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Contact Us