Open In App
Related Articles

Ruby | Matrix collect() function

Improve Article
Improve
Save Article
Save
Like Article
Like

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]]
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 07 Jan, 2020
Like Article
Save Article
Previous
Next
Similar Reads