zoukankan      html  css  js  c++  java
  • ruby collect map seems the function is the same?

      Ruby迭代器each、map、collect、inject
    2010-02-20 15:01
    说明:
    each——连续访问集合的所有元素
    collect—-从集合中获得各个元素传递给block,block返回的结果生成新的集合。
    map——-同collect。
    inject——遍历集合中的各个元素,将各个元素累积成返回一个值。

    例子:
    1. def debug(arr)
    2.     puts '--------'
    3.     puts arr
    4. end
    5.  
    6. h = [1,2,3,4,5]
    7. h1 = h
    8. h1.each{|v|puts sprintf('values is:%s',v)}
    9.  
    10. h2 = h.collect{|x| [x,x*2]}
    11. debug h2
    12.  
    13. h3 = h.map{|x| x*3 }
    14. debug h3
    15.  
    16. h4 = h.inject{|sum,item| sum+item}
    17. debug h4    
    结果:
    1. values is:1
    2. values is:2
    3. values is:3
    4. values is:4
    5. values is:5
    6. --------
    7. 1
    8. 2
    9. 2
    10. 4
    11. 3
    12. 6
    13. 4
    14. 8
    15. 5
    16. 10
    17. --------
    18. 3
    19. 6
    20. 9
    21. 12
    22. 15
    23. --------
    24. 15




    names = %w[ruby rails java python cookoo firebody]
    等同于:
    names = ["ruby", "rails", "java", "python", "cookoo", "firebody"]
  • 相关阅读:
    Spring Security配置logout地址
    flex布局
    视口的学习笔记
    box-sizing属性
    css清除浮动
    line-height的理解
    position和float小结
    css居中方法小结
    margin重叠
    浅谈负margin
  • 原文地址:https://www.cnblogs.com/lexus/p/1871183.html
Copyright © 2011-2022 走看看