Inject a range : inject « Range « Ruby






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

 








Related examples in the same category

1.How many negative numbers?