Ruby/Range/inject

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

How many negative numbers?

(-2..10).inject(0) {|num, x| x<0 ? num+1 : num }  # => 2



Inject a range

sum = (1..5).inject {|total,x| total + x}  # => 15
prod = (1..5).inject {|total,x| total * x} # => 120
max = [1,3,2].inject {|m,x| m>x ? m : x}   # => 3
[1].inject {|total,x| total + x}           # => 1: block never called