Hack hack hack...

An open journal-- some of it written for you, but most of it is for me.

Inject

Learning inject has been on my TODO list for a while…

I want to use inject anytime I am building an object a piece at a time. In the case of summing, creating a hash, or an array I’m building a result by applying changes based on the elements of the enumerable.

Examples
1
2
3
4
5
6
7
8
9
total_visits = stats.inject(0) {|sum, stat| sum = stat.visit_count}

#just for fun let's sum all the numbers from 1 to, oh, say a million
sum = (1..1000000).inject(0){|cummulative,n| cummulative+n}
puts sum   =>500000500000
#you can do interesting things like build hashes
primes = [1,3,5,7,11,13]
hash = primes.inject({}) { |s,e| s.merge( { e.to_s => e } ) }
p hash  #   =>  {"11"=>11, "7"=>7, "13"=>13, "1"=>1, "3"=>3, "5"=>5}

Reading: The inject method Code e.g. - #21e Charles Max Wood Video Treehouse explains the inject method

Comments