# Load an array of 10 ratings by position

Hi all.

I need to load an array with 10 numbers, and place the sum in another
array of numbers as follows: number  + number , number  +
number  and so on. Overall I have to have the following COMBINATIONS:

0+9
1+8
2+7
3+6
4+5
5+4
6+3
7+2
8+1
9+0

This is the code that was doing:

##################################################
srand

rating=[]
result=[]
aux=[]

n=10

for i in 0…n-1
rating[i]=rand(10)+1
end

for i in 4…n-1
aux[i]=rating[i]
end

aux.reverse!

for i in 0…n-1
result[i]=rating[i]+aux[i]
end

puts “#{rating}”
puts “#{result}”
###########################################

Up to half of the array works fine, but after following values

Thanks.

end
end

I’m not sure I understand your question, but you get an error because
you have nils in aux.

Harry

a = (0…9).to_a
b = a.reverse

a.zip(b).collect {|l,r| l + r}

Henry

OFF-TOPIC: This reminded me the trick that famous Carl Gauss did when
his
teacher asked him to calculate the sum of (1…100) =)

On Aug 30, 2012, at 11:17 PM, Andriy A. wrote:

OFF-TOPIC: This reminded me the trick that famous Carl Gauss did when his
teacher asked him to calculate the sum of (1…100) =)

Please be advised that this is primarily a mailing list, and most of the
subscribers receive messages as e-mails. So without the context your
reply does not make much sense. It is a common practice here to provide
essentials of the conversation so that it is clear what you are replying
to.

Sincerely,

Joao S. wrote in post #1073988:

for i in 4…n-1
aux[i]=rating[i]
end

Where does ‘4’ come from? You are iterating over the whole array later,
so you need to copy the whole array. Just changing this to ‘0’ makes

Of course there are simpler ways:

``````aux = rating.reverse
``````

would do the same.

puts “#{rating}”
puts “#{result}”

You don’t need the string interpolation, puts calls to_s on the object
automatically.

In any case I would do:

puts rating.inspect
puts result.inspect

because in ruby 1.8, Array#to_s joins the elements together with no
separator.

As you develop in familiarity, you’ll find that “for” loops are almost
never needed in ruby. For low-level iteration you can use each, or
each_with_index if you need the index for some reason:

rating.each_with_index do |elem,i|
result[i] = elem + aux[i]
end

But then there are other iterators which wrap up common patterns, such
as building a new array from the results of applying a function to the
elements of another array (map/collect).

arr2 = arr1.map { |x| x*2 }

So we don’t need to assign to result[i] explicitly:

result = rating.each_with_index.map { |e,i| e + aux[i] }

And as someone else has shown, given that you reversed the elements into
an aux array, you can zip the elements together and iterate over them
together without using an index.

result = rating.zip(rating.reverse).map { |a,b| a+b }

You’ll get more comfortable with these over time 