Ruby中的每个和collect方法之间有什么区别 [英] what's different between each and collect method in Ruby

查看:114
本文介绍了Ruby中的每个和collect方法之间有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从这段代码中我不知道 collect 每种这两种方法之间的区别。

From this code I don't know the difference between the two methods, collect and each.

a = ["L","Z","J"].collect{|x| puts x.succ} #=> M AA K 
print  a.class  #=> Array

b = ["L","Z","J"].each{|x| puts x.succ} #=> M AA K
print  b.class #=> Array


推荐答案

Array#each 接受一个数组并将给定的块应用于所有项目。它不会影响数组或创建新对象。这只是一种遍历项目的方式。

Array#each takes an array and applies the given block over all items. It doesn't affect the array or creates a new object. It is just a way of looping over items. Also it returns self.

  arr=[1,2,3,4]
  arr.each {|x| puts x*2}

打印2,4,6,8并返回[1,2,3 ,4]无论什么

Prints 2,4,6,8 and returns [1,2,3,4] no matter what

Array#collect Array#map ,它将给定的代码块应用于所有项目并返回新数组。只需将将序列的每个元素投影到新表单中

Array#collect is same as Array#map and it applies the given block of code on all the items and returns the new array. simply put 'Projects each element of a sequence into a new form'

  arr.collect {|x| x*2}

返回[2,4,6,8]

Returns [2,4,6,8]

然后在您的代码中

 a = ["L","Z","J"].collect{|x| puts x.succ} #=> M AA K 

a是一个数组,但实际上是Nil的 [nil, nil,nil] ,因为放入x.succ 会返回 nil (即使它会打印M AA K) 。

a is an Array but it is actually an array of Nil's [nil,nil,nil] because puts x.succ returns nil (even though it prints M AA K).

 b = ["L","Z","J"].each{|x| puts x.succ} #=> M AA K

也是一个数组。但是它的值为[ L, Z, J],因为它返回了self。

also is an Array. But its value is ["L","Z","J"], because it returns self.

这篇关于Ruby中的每个和collect方法之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆