Skip to content
Related Articles

Related Articles

Improve Article
Ruby | Matrix collect() function
  • Last Updated : 07 Jan, 2020

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]]
My Personal Notes arrow_drop_up
Recommended Articles
Page :