Ruby中map,reduce,reject,select,collect,each使用介绍

Ruby学习中,对这几个方法用法记下。

# map 针对每个element进行变换并返回整个修改后的数组
def map_method
  arr1 = ["name2", "class2"]
  arr1.map {|num| num + "and"}
  print "map ====",arr1, "\n"
end

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

def map2_method
  arr1 = ["name3", "class3"]
  # &:表示item
  arr2 = arr1.map(&:upcase)
  print "map2 ====", arr2, "\n"
end
# reduce  把array变换为一个值后返回
def reduce_method
  arr1 = ["a", "b", "c", "d"]
  arr2 = arr1.reduce(:+)
  print "reduce ====", arr1, "\n"
  print "reduce ====", arr2, "\n"
end

def reduce_method2
  sum1 = (1..100).reduce(:+)
  sum2 = (1..100).reduce(0) do |sum, value|
    sum + value
  end
  print "reduce sum1 ====#{sum1}\n"
  print "reduce sum2 ====#{sum2}\n"
end

# select 根据条件返回一个子集
def select_method
  arr = (1..8).select {|x| x % 2 == 0}
  print "select ====", arr, "\n"
end

#reject 根据条件提出一个子集
def reject_method
  arr = (1..8).reject {|x| x % 2 == 0}
  print "reject ====", arr, "\n"

end

#each 遍历数组每个元素,但不生成新的数组
def each_method
  arr1 = ["name2", "class2"]
  arr2 = arr1.each {|num| num + "and"}
  print "each ====", arr2, "\n"
end

#collect 同map一样,collect!同map!一样
def collect_method
  arr1 = ["name2", "clas2"]
  arr2 = arr1.collect { |num| num + "and" }
  print "collect ====", arr2, "\n"
end

map_method
map1_method
map2_method
reduce_method
select_method
reject_method
each_method
collect_method
reduce_method2
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、异同对比选择1、Python和ruby的相同点: * 都强调语法简单,都具有更一般的表达方式。python是缩...
    沃伦盖茨阅读 4,200评论 2 24
  • 在本教程中,将探讨使用Ruby开始编程所需的基本语法,以及如何在30分钟内快速入门学习并使用Ruby编程语言。 注...
    易百教程阅读 7,333评论 1 36
  • 我想和你生一个孩子 我们一起决定他的样子 兴致勃勃的讨论他这怪脾气 宠着他吃肉喝酒抽烟打网游 走我们走过的路, 或...
    瑾儿1996阅读 250评论 0 1
  • 父母总是很奇怪,大学千叮呤万嘱咐,好好学习,学业为主,争取保研,不要一心扑到爱情里不能自拔。在父母给白宇灌输了一系...
    柳小鱼鱼阅读 719评论 3 11
  • 1.在表格中的td,实现文字溢出省略 只对单行文字有效,对多行省略不起作用 2.单行超出隐藏 固定属性 3.多行超...
    LuckyS007阅读 20,889评论 0 0