Help me with this part of code:
class Ooo
attr_accessor :class_array
end
def func(ctx)
local_array = ctx.class_array
local_array = [4,3,5,5,6]
return
end
aaa = Ooo.new
func(aaa)
aaa.class_array => not [4,3,5,5,6] :-(
I supposed that ruby use addresses when operates with arrays…
Why does this code not work?
I want to do this (in C):
struct ctx
{
uint class_array[10000]
}
void func(struct *ctx)
{
uint* local_array = &ctx->class_array
local_array[0] = 4;
ctx->class_array[0] => 4
}
The problem is with this part of code:
This doesn’t do what you think it does. The second line creates a new list and assigns it to the local variable, thus replacing the reference to
ctx.class_array. It will not touchctx.class_array. An equivalent piece of C code would work the same way, so I think you don’t only have a Ruby problem here.In C you could use pointers to solve this. In Ruby you probably want either:
or simply (much better!)
By the way, the direct translation of your C program would also work: