红宝石 |矩阵收集()函数
collect()是 Ruby 中的一个内置方法,在执行块中给出的操作后返回新矩阵。
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.
示例 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}
输出:
Matrix[[3, 63], [93, 54]]
示例 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}
输出:
Matrix[[33, 21, 25], [32, 21, 25], [31, 22, 25]]