Ruby/Array/inject
Материал из Wiki.crossplatform.ru
Building Up a Hash Using Injection
collection = [ [1, "one"], [2, "two"], [3, "three"], [4, "four"], [5, "five"] ] collection.inject({}) do |hash, value| hash[value.first] = value.last hash end p collection # => {5=>"five", 1=>"one", 2=>"two", 3=>"three", 4=>"four"}
Sum an array with inject
collection = [1, 2, 3, 4, 5] collection.inject(0) {|sum, i| sum + i} # => 15
Sum of word lengths
%w[pea queue are].inject(0) {|total, word| total + word.length } # => 11