Ruby之map、each、collect、map!、collect!揭秘


def map_method
arr1 = ["name2","class2"]
arr2 = arr1.map {|num| num + "and"}
print "map............",arr2,"\n"
end

def each_method
arr1 = ["name2","class2"]
arr2 = arr1.each {|num| num + "and"}
print "each............",arr2,"\n"
end

def collect_method
arr1 = ["name2","class2"]
arr2 = arr1.collect {|num| num + "and"}
print "collect............",arr2,"\n"
end

def map1_method
arr1 = ["name2","class2"]
arr2 = arr1.map! {|num| num + "and"}
print "map!............",arr2,"\n"
end

def collect1_method
arr1 = ["name2","class2"]
arr2 = arr1.collect! {|num| num + "and"}
print "collect!............",arr2,"\n"
end

def test
map_method
each_method
collect_method
map1_method
collect1_method
end

test


result:
map............["name2and", "class2and"]
each............["name2", "class2"]
collect............["name2and", "class2and"]
map!............["name2and", "class2and"]
collect!............["name2and", "class2and"]

为了更明了的了解each的用法,看下面的例子:

def each_deep_method
arr_test = [1,2,3]
arr_result = arr_test.each do |num|
num = num + 1
p num
end
arr_result
end

result:
2
3
4
=> [1, 2, 3]
可见each_deep_method的返回值arr_result是和arr_test相等的。
[总结]
(1)each只是遍历数组的每个元素,并不生成新的数组;
(2)map和collect相同用法,遍历每个元素,用处理之后的元素组成新的数组,并将新数组返回;
(3)map!同collect!
其中map和map!、collect和collect!的区别就不用纠结了吧,实在纠结就看下面的例子:

def map_deep_method
arr_test = [1,2,3]
arr_test.map do |num|
num += 1
end
arr_test #[1, 2, 3]
end

def map1_deep_method
arr_test = [1,2,3]
arr_test.map! do |num|
num += 2
end
arr_test #[3, 4, 5]
end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值