Robert Klemme
1/24/2007 11:21:00 AM
On 24.01.2007 11:34, Maxime Guilbot wrote:
> Look at the code below, I got strange results, I know that there is a
> problem in the code but I can't find it. I expect to have an array like
> this:
>
> [[4, 4], [8, 1024], [1024, 1024], [1024, 1024], [1024, 1024], [1024,
> 1024], [1024, 1024], [1024, 1024], [1024, 1024], [1024, 1024]]
>
> at the ouput of get_next_10...
>
> Does someone has the idea?
Your problem is aliasing: you're reusing the same @indexes over and over
again.
> Thanks a lot,
> Maxime.
>
> class Dummy
> def initialize
> @indexes = Array.new(2, 1)
> end
>
> def get_next
> @indexes[0] = @indexes[0]*2
> @indexes[1] = @indexes[1]*2
>
> @indexes
Make that @indexes.dup or do get_next.dup in get_next_10.
> end
>
> def get_next_10
> all = []
> for i in 0..9
> all << get_next
> end
> all
> end
> end
> => nil
>
> d = Dummy.new
> => #<Dummy:0x33b198 @indexes=[1, 1]>
>
> d.get_next_10
> => [[1024, 1024], [1024, 1024], [1024, 1024], [1024, 1024], [1024,
> 1024], [1024, 1024], [1024, 1024], [1024, 1024], [1024, 1024], [1024,
> 1024]]
>
> d.get_next
> => [2048, 2048]
>
> d.get_next
> => [4096, 4096]
Kind regards
robert