views:

131

answers:

2

The following modify method somehow modifies the whole @x array instead of just simply generating another element to be pushed later. How come?

def modify i, s
  t = @x[-1]
  t[i] = t[i] + s
  t
end

@x = [ [10, 12] ]
@x << modify(0, 1)

puts @x

Edited The following code have done the trick. Still I wonder if its possible to get rid of the p-argument

def modify p, i, s
  a = p.to_a
  a[i] += s*@delta[i]
  Vector.elements( a )
end
A: 

@x[-1] is the inner array [10, 12]. You set t to reference this array. You then modify this array with the t[i] = part.

Chuck
how do I set t-variable not to reference, but to only pick the value?
gmile
Clone it. `t = @x[-1].clone`
Chuck
lose the t[i]= and replace it with any new variable
avguchenko
@avguchenko: As I said in the comments to your answer, that wouldn't have the desired effect. He appears to want a modified version of the array. Replacing the mutation of `t` with a variable holding a single element of `t` doesn't work.
Chuck
+1  A: 

You should probably redo from start, but in the spirit of small changes ... try changing your method to reduce side effects.

If you want to return a single Fixnum element:

def modify i, s
  t = @x[-1]
  r = t[i] + s
  r
end

or, if you want to return an array to inject into the greater array of tuples

def modify i, s
  t = @x[-1].dup
  t[i] = t[i] + s
  t
end

In the spirit of understanding, you should read up on Ruby objects and how they are references and how Ruby methods have has side-effects.

Study this:

a=[1,2]
b=a
b[0]=4
puts a
> [4,2]

You might want to do a dupe

a=[1,2]
b=a.dup
b[0]=4
puts a
> [1,2]
avguchenko
too many sub-variables... is there a chance to pass the value, not the *link* ?
gmile
@Bob Aman: here we do not need the dupe because i changed t[i]=... to r=...
avguchenko
This not only removes the side-effect, it also changes the return type of the method. Previously, it returned an array. This version returns an integer. Since it appears to be an array of arrays, this is probably incorrect.
Chuck
I think we can all agree that there are numerous problems with gmile's example.
jrhicks
@Chuck: the question specified that he wanted to generate "another element to be pushed later." I think this is a side effect of the vagueness of the question. I do not feel the downvote is fair.
avguchenko