# 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