Ruby 中的 each 和 collect 方法有什么不同 [英] what's different between each and collect method in Ruby

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

问题描述

从这段代码我不知道collecteach这两种方法的区别.

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#collectArray#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] 数组,因为 puts 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 中的 each 和 collect 方法有什么不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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