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
your program work.
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