Open In App

Ruby | Matrix collect() function

The collect() is an inbuilt method in Ruby returns the new matrix after performing the operation that is given in the block.

Syntax: mat1.collect{|el| operation}



Parameters: The function has the parameter as a block which is the operation which is performed on all elements.

Return Value: It returns the new matrix after performing the operation on all elements.



Example 1:




# Ruby program for collect() method in Matrix
  
# Include matrix 
require "matrix"
  
# Initialize a matrix 
mat1 =  Matrix[[1, 21], [31, 18]]  
  
# Prints the value of mat1.collect
# after multiplying all elements by 3 
puts  mat1.collect{|el| el*3}

Output:

Matrix[[3, 63], [93, 54]]

Example 2:




# Ruby program for collect() method in Matrix
  
# Include matrix 
require "matrix"
  
# Initialize a matrix 
mat1 = Matrix[[13, 1, 5], [12, 1, 5], [11, 2, 5]]  
  
# Prints the value of mat1.collect
# after adding 20 to all the elements 
puts  mat1.collect{|el| el+20}

Output:

Matrix[[33, 21, 25], [32, 21, 25], [31, 22, 25]]
Article Tags :