zoukankan      html  css  js  c++  java
  • Ruby中map, collect,each,select,reject,reduce的区别

    # map 针对每个element进行变换并返回整个修改后的数组
    def map_method
      arr1 = ["name2", "class2"]
      arr1.map {|num| num + "and"}
      print "map ====",arr1, "
    "
    end
    
    def map1_method
      arr1 = ["name2", "class2"]
      arr1.map! {|num| num + "and"}
      print "map! ==== ", arr1, "
    "
    end
    
    def map2_method
      arr1 = ["name3", "class3"]
      # &:表示item
      arr2 = arr1.map(&:upcase)
      print "map2 ====", arr2, "
    "
    end
    # reduce  把array变换为一个值后返回
    def reduce_method
      arr1 = ["a", "b", "c", "d"]
      arr2 = arr1.reduce(:+)
      print "reduce ====", arr1, "
    "
      print "reduce ====", arr2, "
    "
    end
    
    def reduce_method2
      sum1 = (1..100).reduce(:+)
      sum2 = (1..100).reduce(0) do |sum, value|
        sum + value
      end
      print "reduce sum1 ====#{sum1}
    "
      print "reduce sum2 ====#{sum2}
    "
    end
    
    # select 根据条件返回一个子集
    def select_method
      arr = (1..8).select {|x| x % 2 == 0}
      print "select ====", arr, "
    "
    end
    
    #reject 根据条件提出一个子集
    def reject_method
      arr = (1..8).reject {|x| x % 2 == 0}
      print "reject ====", arr, "
    "
    
    end
    
    #each 遍历数组每个元素,但不生成新的数组
    def each_method
      arr1 = ["name2", "class2"]
      arr2 = arr1.each {|num| num + "and"}
      print "each ====", arr2, "
    "
    end
    
    #collect 同map一样,collect!同map!一样
    def collect_method
      arr1 = ["name2", "clas2"]
      arr2 = arr1.collect { |num| num + "and" }
      print "collect ====", arr2, "
    "
    end
    

     

  • 相关阅读:
    beta冲刺(6/7)
    beta冲刺(5/7)
    beta冲刺(4/7)
    beta(3/7)
    beta冲刺(2/7)
    beta冲刺(1/7)
    团队项目测评博客
    东华理工18级计科五班团队作业六
    东华理工18级计科五班团队作业五
    东华理工18级计科五班团队作业四
  • 原文地址:https://www.cnblogs.com/gdpdroid/p/6767183.html
Copyright © 2011-2022 走看看