→ Use inject! Change three lines of code into one! Use inject! Stop repeating yourself! → → →

Which three lines you keep repeating all over again? Initializing variable? Iterating over collection and inserting into that variable? Returning that variable? Do it in one line!

numbers_asc = [1,2,3,4,5,6]
squares_desc = numbers_asc.reverse.inject([]) {|aggr,v| aggr << v**2}

#the line above instead of three lines below!
#squares_desc = []
#numbers_asc.reverse.each {|n| squares_desc << n**2}
#squares_desc #this third line is used to return value (typically from method)

p squares_desc

Output, as it's easy to guess is:

[36, 25, 16, 9, 4, 1]

It works! Use it!

Created on 13 May 2009