Ruby之map、each、collect、map!、collect!揭秘
来源:互联网 发布:三拼域名 不值钱 编辑:程序博客网 时间:2024/05/16 18:23
- 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
阅读全文
0 0
- Ruby之map、each、collect、map!、collect!揭秘
- Ruby中each,map,collect,inject对比
- Ruby中的each collect map inject
- Ruby中map,reduce,reject,select,collect,each使用介绍
- ruby的collect或者map
- ruby的collect或者map
- ruby的collect或者map
- ruby , each,map,collect,inject,reject,select,shuffle[n..m],flatten
- ruby中的join,split,send,map,each,collect,inject方法总结
- ruby , each,map,collect,inject,reject,select,shuffle[n..m],flatten
- Ruby迭代器each、map、collect、inject、times、upto、step、for in
- map的collect和spill过程解析
- ruby on rails 里pluck和select(map、collect)的区别
- collect!
- collect
- Collect
- Collect Set List HashSet ArrayList LinkedList TreeSet Map HashMap TreeMap
- RDD应用API---flatMap、map、reduceByKey、collect、foreach
- 如何安装centos系统,并且使用xshell进行简单静态ip设置
- bzoj 1688: [Usaco2005 Open]Disease Manangement 疾病管理(状压)
- 存储过程,函数,触发器
- c++多线程重点难点(四)semaphore
- windos nginx curl 超时
- Ruby之map、each、collect、map!、collect!揭秘
- 种子生长相关算法实现
- HALCON里几种数据类型详解
- 虚拟机安装Linux
- sql 计算两经纬度之间的距离
- spring boot整合RabbitMQ(Topic模式)
- 接口开发 face++人脸检测
- 常用的sharePreference工具类
- 汉诺塔的java递归实现