If you just need an amount, here is an easy way:
tablica = [ 23,53,23,13 ] puts tablica.inject(0){|sum,current_number| sum+current_number}
For the first two elements (or any adjacent range) you can use a range:
tablica = [ 23,53,23,13 ] puts tablica[0..1].inject(0){|sum,current_number| sum+current_number}
What does it do:
- A block (statement inside
{...} ) is called inside inject , once for each element of the array. - At the first iteration,
sum has an initial value of 0 (which we passed to inject ) And current_number contains the 0th element in the array. - We add two values ββ(0 and 23), and this value is assigned to
sum when the block returns. - Then, at the next iteration, we get the variable
sum as 23 and current_number as 53. And the process repeats.
source share