Topic: Beginner question about integer arrays

Hello

Maybe I'm sitting to long in front of my computer, but I don't see what's wrong here...
I just want to initialize an int Array and add some values to the elements in the array, but it seems that this is completely different to java for example.

def test
  te = Array.new(5)
  te.each do |t|
     t = 10
  end

  puts "stop"
  puts te[0].to_i
  puts te[0]
  puts "end"
end

and the output is:

stop
0

end

although i would think that the result is 10 at least in one case.
and when i do this:

def test
  te = Array.new(5)
  te.each do |t|
    t = 10
  end
  te[1] += 100
end

the result is:

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.+

I hope someone can help me with this basic question...

Regards,
Chang

Re: Beginner question about integer arrays

You have created an array with one element using
te = Array(5)
if you wanted to declare an array with 5 elements, I would use
te = Array.new(5)
which declares an array with (5) nil elements

This should work well for a simple Array assignment. There are other ways you can also inquire about.

te = Array.new(5)
0.upto(5) do |t|
te[t] = 10
end

Re: Beginner question about integer arrays

Hi quakerStarter

Thanks for your help.
It works now.


Chang