Ruby 矩阵 collect()函数
collect() 是Ruby中一个内置的方法,在执行了块中给出的操作后,返回新的矩阵。
语法 :mat1.collect{|el|operation}。
参数 :该函数的参数是一个块,是对所有元素进行的操作。
返回值 :在对所有元素进行操作后,返回新矩阵。
例子 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]]