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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Array#eachtakes 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.Prints 2,4,6,8 and returns [1,2,3,4] no matter what
Array#collectis same asArray#mapand 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’Returns [2,4,6,8]
And In your code
a is an Array but it is actually an array of Nil’s [nil,nil,nil] because
puts x.succreturnsnil(even though it prints M AA K).And
also is an Array. But its value is [“L”,”Z”,”J”], because it returns self.