How to count in a loop?

I'm new to Ruby, how can I count elements in a loop? In Java, I would write this as follows

int[] tablica = { 23,53,23,13 }; int sum = 0; for (int i = 0; i <= 1; i++) { // **only first two** sum += tablica[i]; } System.out.println(sum); 

EDIT: I only want the first two

+4
source share
5 answers
 tablica.take(2).reduce(:+) 

But seriously? What's wrong with

 tablica[0] + tablica[1] 

Hey, he even works in Ruby and Java & hellip; and C, C ++, Objective-C, Objective-C ++, D, C #, ECMAScript, PHP, Python. Without changes.

+4
source

You can sum all the elements of the array as follows:

 arr = [1,2,3,4,5,6] arr.inject(:+) # any operator can be here, it will be # interpolated between the elements (if you use - for example # you will get 1-2-3-4-5-6) 

Or if you want to iterate over the elements:

 arr.each do |element| do_something_with(element) 

Or if you need an index too:

 arr.each_with_index do |element, index| puts "#{index}: #{element}" 
+5
source

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.
+1
source

There are many ways, but if you want the current object and counter to use each_with_index

 some_collection.each_with_index do |o, i| # 'o' is your object, 'i' is your index end 

EDIT: Oh, read it too fast. You can do it

 sum = 0 some_collection.each { |i| sum += i } 
+1
source

With Enumerable # inject :

 tablica = [23, 53, 23, 13] tablica.inject(0, :+) # 112 
+1
source

Source: https://habr.com/ru/post/1334554/


All Articles