Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count in a loop?

Tags:

loops

ruby

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

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 want only first two

like image 773
IAdapter Avatar asked Dec 16 '22 18:12

IAdapter


1 Answers

You can sum all the elements in an array like this:

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 the index too:

arr.each_with_index do |element, index|
    puts "#{index}: #{element}"
like image 104
Gabi Purcaru Avatar answered Dec 19 '22 08:12

Gabi Purcaru