好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

ruby collect map seems the function is the same?

ruby collect map seems the function is the same?

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

例子:

def debug ( arr )     puts   ' -------- '     puts   arr end   h = [ 1 , 2 , 3 , 4 , 5 ] h1 = h h1 . each {| v | puts   sprintf ( ' values is:%s ' , v ) }   h2 = h . collect {| x | [ x , x * 2 ] } debug   h2   h3 = h . map {| x | x * 3 } debug   h3   h4 = h . inject {| sum , item | sum + item }

debug   h4    

结果:

values is:1 values is:2 values is:3 values is:4 values is:5 -------- 1 2 2 4 3 6 4 8 5 10 -------- 3 6 9 12 15 -------- 15



names = %w[ ruby rails java python cookoo firebody]
等同于:
names = [" ruby ", "rails", "java", "python", "cookoo", "firebody"]

查看更多关于ruby collect map seems the function is the same?的详细内容...

  阅读:50次