Open In App

Ruby | Array class each() operation

Last Updated : 08 Jan, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Array#each() : each() is a Array class method which returns the array by following the condition in the given block once for each element in self.

Syntax:  Array.each()

Parameter:  block - condition to follow

Return:  Each array element following the condition

Code #1 : Example for each() method




# Ruby code for each() method
  
# declaring array
a = ["abc", "nil", "dog"]
  
# declaring array
b = ["hello", "hi", "dog"]
  
# each
puts "each : #{a.each {|x| print x, " -- "}}\n\n"


Output :

abc -- nil -- dog -- each : ["abc", "nil", "dog"]

Code #2 : Example for each() method




# Ruby code for each() method
  
# declaring array
a = ["abc", "nil", "dog"]
  
# declaring array
b = ["hello", "hi", "dog"]
  
  
# each
puts "each : #{b.each{|x| x = 2}}\n\n"
     


Output :

each : ["hello", "hi", "dog"]

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads