Ruby collect or map

Recommended for you: Get network issues from WhatsUp Gold. Not end users.
Ruby collect or map
Explain:
each-Continuous access to all elements of the set
collect—For each element from the collection passed to the block, generate a new set of block results returned.
map-- same as collect.
inject-Through every element in the set, the accumulation of elements to return avalue.

Example:

def debug(arr) puts '--------' puts arrend h = [1,2,3,4,5]h1 = hh1.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}The results of debug H4:
values is:1values is:2values is:3values is:4values is:5--------12243648510--------3691215--------15
names = %w[ruby rails java python cookoo firebody]
Equal to:
names = ["ruby", "rails", "java", "python", "cookoo", "firebody"]


ids = @pages.collect { |p| p.id }.join(',')

The IDS classlike: 23,32,53,64,155

Remove all meet the requirements of the ID
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Elsa at January 25, 2014 - 3:02 PM