开发者

Distinct difference between collect and each? [duplicate]

开发者 https://www.devze.com 2023-01-14 00:54 出处:网络
This question already has answers here: what's different between each and collect method in Ruby [duplicate]
This question already has answers here: what's different between each and collect method in Ruby [duplicate] (7 answers) Closed 8 years ago.

Using arrays what's the main difference between collect and each? Preferen开发者_运维知识库ce?

some = []

some.collect do {|x| puts x}

some.each do |x|
    puts x
end


array = [] is a shortcut to define an array object (long form: array = Array.new)

Array#collect (and Array#map) return a new array based on the code passed in the block. Array#each performs an operation (defined by the block) on each element of the array.

I would use collect like this:

array = [1, 2, 3]
array2 = array.collect {|val| val + 1}

array.inspect # => "[1, 2, 3]"
array2.inspect # => "[2, 3, 4]"

And each like this:

array = [1, 2, 3]
array.each {|val| puts val + 1 }
# >> 2
# >> 3
# >> 4
array.inspect # => "[1, 2, 3]"

Hope this helps...


collect (or map) will "save" the return values of the do block in a new array and return it, example:

some = [1,2,3,10]
some_plus_one = some.collect {|x| x + 1}
# some_plus_one == [2,3,4,11]

each will only execute the do block for each item and wont save the return value.

0

精彩评论

暂无评论...
验证码 换一张
取 消