From: Todd Benson Date: 2008-03-24T18:13:43+09:00 Subject: Re: functions, arguments and changing their value permantently On Mon, Mar 24, 2008 at 3:12 AM, Adam Akhtar wrote: > Im coming over to Ruby from C++ after a long break from programming. One > thing im having to get used to is how ruby references or points directly > to variables. In C++ I can pass a variable as an argument to a function > and then change the value within the function. This change will be > reflected outside of the function. How do i go about doing this in ruby? > > i.e. > > x = 10 > > def changeit var > var = 20 > end > > changeit x > puts x > ==> 20 Ruby tries to maintain scope rigidly. So your x before will not change within the scope of the method changeit. Your method, when called, says... changeit 10 Then you want to do assignment as... x = 20 It's a different x! You can pull out of local scope with class instance variables or globals. Your same code, just changed... @x = 10 def changeit n @x = n end ...or return it directly form the method if that's the only value you need x = 10 def changeit n n end x = changeit ...in which case you would probably want to rename the method. I have to say, I don't see this as a good design pattern using Ruby, but I don't know what you're trying to do :) I can't tell by your post, but if really what you want to do is send a variable "name" into the method and have the method change the value. That's different and might require some brainiacs on the list to help you (my guess is that you would have use some form of #eval). Todd