On Jun 23, 2007, at 10:45 PM, Starke wrote:

> Im trying to set up a method and pass a varible to it then out put the
> new manipulated varible back out.   Here is what I have
>
>
> ---------------------------------
> var1 = 'test'
>
> def change var_in
>   puts var_in
>   var_in = 'test1'
>   puts var_in
> end
>
> change var1
>
> -----------------------------------
>
> As you can see, I pass in var1 into the method and then I change the
> value to 'test1'.  I would like to method to go back and update var1,
> so that if passed into another method it reflects the change that
> method change var_in did.  Does this make since?  Im new to
> programming.

A simple approach is to add one line of code at the end of your  
'change' method, so the new value is returned, and then assign 'var1'  
to that value.

var1 = 'test'

def change var_in
   puts var_in
   var_in = 'test1'
   puts var_in
   var_in # Ruby returns the value of last expression evaluated in a  
method
end

var1 = change var1 # this is a common Ruby idiom for updating a variable
var1 # => "test1"

Because the value you are returning is independent of the argument  
'var_in', if the 'puts' weren't there, the whole thing could be  
reduced to:

var1 = 'test'

def change
   'test1'
end

var1 = change
var1 # => "test1"

But that's too trivial, so let's look at a version where 'change'  
depends on its argument:

var1 = 'test'

def change var_in
    "#{var_in} contains #{var_in.size} characters"
end

var1 = change var1
var1 # => "test contains 4 characters"

Regards, Morton