Andreu <root@sys1.org> writes:
Please consider the following code:
def myfunct
ie = 0
0.step(il, 3) do |i|
dmy = ilines[i+1]
icatn[ie] = dmy[2,5]
idate[ie] = dmy[18,5]
ie += 1
end
me = 0
0.step(ml, 3) do |j|
dmy = mlines[j+1]
mcatn[me] = dmy[2,5]
mdate[me] = dmy[18,5]
me += 1
end
end
When the program exits the first loop, the contents of array idate is OK.
When the second loop is exited, the array variable idate have the same
contents as mdate ...
Any clue welcomed, thanks, Andreu.
You've left out some important info, but aren't you assigning the same
values to both arrays?
idate[ie] = dmy[18,5]
...
mdate[me] = dmy[18,5]
···
--
Brian Adkins
http://www.lojic.com/
* Andreu <root@sys1.org> (2008-11-07) schrieb:
PROBLEM SOLVED
At the beginning of my program I have written this line:
idate = mdate = Array.new
but it seems Ruby doesn't support this syntax (like C) and assume
that the two arrays are the same one.
Actually Ruby and C do the same thing here: Assign whatever Array.new
yields to mdate and idate.
mfg, simon .... l
It's not a difference in syntax, but a difference in how variables are
handled. When you write something like this in C:
int a, b;
a = b = 0;
You are creating two variables on the stack and assigning an integer
to them. The actual value 0 is stored in borth variables because they
are intrinsic types that have been allocated on the stack.
When you write in Ruby:
idate = mdate = Array.new
something different happens. Array.new returns a reference to an
instance of array that has been allocated on the heap. The variable
mdate holds the value of the reference, not the instance itself. This
same reference is then assigned to idate. Now both variables have a
reference to the same instace on the heap.
A reference is really just a pointer with nicer semantics. If you're
familiar with a language that has pointers, like C, then think of it
like this:
int * GetInt()
{
int * i = (int *) malloc(sizeof(int));
return i;
}
int * i, * j;
i = j = GetInt();
Now if you modify j:
*j = 5;
printf("%d", *i); // prints "5"
···
On Fri, 07 Nov 2008 23:33:12 +0100, Andreu <root@sys1.org> wrote in <gf2flo$te8$1@aioe.org>:
PROBLEM SOLVED
At the beginning of my program I have written this line:
idate = mdate = Array.new
but it seems Ruby doesn't support this syntax (like C) and assume
that the two arrays are the same one.
--
Charles Calvert | Web-site Design/Development
Celtic Wolf, Inc. | Software Design/Development
http://www.celticwolf.com/ | Data Conversion
(703) 580-0210 | Project Management