Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

What is “each{ } method” in Ruby?

okwudili onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The each{} method allows one loop through the elements of an array to perform operations on them.

It is an enumerator function that allows you to iterate over elements of an array and returns an array.

Syntax

array_name.each{block}

Parameters

  • {block}: This is the loop that is executed. It takes a parameter which represents each element in the array and a function that will be performed on each element. See the example below:
[1,2,3,4].each{|elem| puts elem}
  • In the snippet above, the block takes elem as a parameter and prints the value to the console. elem here represents each element of the array. So the result will be:
1
2
3
4

Return value

It returns the array itself. For example the array above, [1,2,3,4] is what will be returned after each method is called on it.

Example

In the code below, the functionality of the each{} method will be applied to the elements of an array.

# create an array
array = ["Google", "Netflix", "Amazon", "Apple", "Meta"]
# use each method
a = array.each {|elem| puts elem}
An example of each method in Ruby

From the code above, the each{} method was used to loop through the array array. As it looped, it printed each element in the array.

Now, let’s take it further. Let’s loop through the array and print the first character of each element.

# create an array
array = ["Google", "Netflix", "Amazon", "Apple", "Meta"]
# use each method
a = array.each {|elem| puts "#{elem} = #{elem[0,1]}" }
Print First Characters of elements in an array using each method

RELATED TAGS

ruby
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring