Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change variable passed in a method [duplicate]

How can I change the contents of a variable using a method? Maybe I'm not saying this correctly. What is a way to get the reference to a variable like in C? Example:

// main stuff
int gorilla = 29;
makeMeABanana(&gorilla);

void makeMeABanana(int *gorilla) { }

How can I do something like this in Ruby?

like image 939
Imnotanerd Avatar asked May 05 '11 22:05

Imnotanerd


People also ask

How do you pass a variable from one method to another?

You can't. Variables defined inside a method are local to that method. If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).

Can you change variables in Java?

Remember that a variable holds a value and that value can change or vary. If you use a variable to keep score you would probably increment it (add one to the current value).

Can you change a global variable in a function C++?

Functions can access global variables and modify them. Modifying global variables in a function is considered poor programming practice. It is better to send a variable in as a parameter (or have it be returned in the 'return' statement).


1 Answers

You should not do this - you're just porting techniques that are fully appropriate to C to Ruby, where they are no longer appropriate. There are several fancy ways around this (eg using a Proc closed over your calling namespace, or eval) but they are usually inappropriate in Ruby unless you know precisely what you're doing.

like image 74
Peter Avatar answered Sep 30 '22 05:09

Peter