开发者

How to count in a loop?

I'm new to Ruby, how can I count elements in a loop? In Java I would w开发者_运维问答rite 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


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}"


tablica.take(2).reduce(:+)

But seriously? What's wrong with just

tablica[0] + tablica[1]

Hey, it even works in Ruby and Java … and C, C++, Objective-C, Objective-C++, D, C#, ECMAScript, PHP, Python. Without changes.


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

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

EDIT: Oops, read that too quickly. You can do this

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


With Enumerable#inject:

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


If you just need a sum, here is a simple way:

tablica = [ 23,53,23,13 ]
puts tablica.inject(0){|sum,current_number| sum+current_number}

For first two elements (or whatever contiguous range) you can use a range:

tablica = [ 23,53,23,13 ]
puts tablica[0..1].inject(0){|sum,current_number| sum+current_number}

What this does:

  1. The block (the statement within {...}) is called internally by inject, once for each element in the array.
  2. At the first iteration, sum has the initial value 0 (that we passed to inject) And current_number contains the 0th element in the array.
  3. We add the two values (0 and 23) and this value gets assigned to sum when the block returns.
  4. Then on the next iteration, we get sum variable as 23 and current_number as 53. And the process repeats.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜