views:

50

answers:

2

This is psesudo code. In what programming language this is possible ?

def lab(input)
  input = ['90']
end

x = ['80']
lab(x)

puts x #=> value of x has changed from ['80'] to ['90]

I have written this in ruby but in ruby I get the final x value of 80 because ruby is pass-by-reference. However what is passed is the reference to the data held by x and not pointer to x itself same is true in JavaScript. So I am wondering if there is any programming language where the following is true.

+1  A: 

There are several languages that support pass-by-reference: it was implicit in most Fortran versions for longer than most other programming languages have existed (some versions used copies back and forth, but the end result had better be the same;-), it was specified by var in Pascal in the '70s (though the default, if you didn't say var, was by copy), etc, etc.

Most modern languages (Java, Python, Ruby, Javascript, Go, ...) uniformly pass (and assign) by object-reference (which is what you call "reference to data"), though some are more complex and let you specify more precisely what you want (e.g., C++, C#).

Alex Martelli
"reference to data" . First time I heard this term but seems like an apt name. Thanks for the answer.
Nadal
+1  A: 

So in Ruby, you can't make x reference another object from within a method, but you can change the object itself, in your case what you want can be achieved using mutating methods (Array#replace could be handy in case of arrays, for example):

def lab input
  input.replace ['90']
end

x = ['80']
#=> ["80"]
lab x
#=> ["90"]
x
#=> ["90"]
Mladen Jablanović
The point being that your problem wasn't in passing the variable, it was that `input = ['90']` reassigns the local variable 'input' to a new array object. `input.replace` changes the contents of the existing object, which is what you were trying to do.
glenn mcdonald
I'm not sure if I understand you; I stated at the beginning that one can't reassign variable `x` from within the method in Ruby, just mutate its content.
Mladen Jablanović