From: "Abinoam Jr." Date: 2011-01-18T09:24:53+09:00 Subject: Re: Calling by Reference - Two Questions I think I didn't understand your question correctly, sorry (My english skills are not so good). But, see bellow and tell me if this is what you want. def myswap(arr) [arr[1], arr[0]] end def myswap!(arr) arr[0], arr[1] = arr[1], arr[0] end def myswap2!(arr) arr[0], arr[1] = arr[1], arr[0] arr end a = [2, 5] myswap a # => [5,2] (new object) myswap! a # => [5,2] (a now is changed; note that the returned array is not a) myswap2! a # => [5,2] (a now is changed; the returned array is "a" (same object_id) ) Abinoam Jr. On Mon, Jan 17, 2011 at 9:07 PM, Mike Stephens wrote: > I know I'm not the first person to get stumped by how to get Ruby to > change an object in a method. > > I want to do: > > method a1 or a1.method > > I can do > >  a1 = method a1 > > but amongst other things that creates a new object. > > a1 = [1,2] > puts " #{a1} # 12 > > def myswap1(a2) >  a3 = [0,0] >  a3[0] = a2[1] >  a3[1] = a2[0] >  a2 = a3 >  end > > myswap1 a1 > puts " #{a1} " # 12 > > Ruby passes in a1, so at the start of the method a2 is the same > reference as a1. However when I assign a1 = a3, a1 becomes a different > reference and disappears when the method terminates. > > So my first question is why won't Ruby let me do this: > > a1 = [1,2] > > public > def myswap5 >  a3 = [0,0] >  a3[0] = self[1] >  a3[1] = self[0] >  self = a3 >  end > > a1.myswap5 # gives error message: Can't change the value of self > > My second question is from this: > > a1 = [1,2] > > def myswap6(a2) >  a2.reverse! >  end > >  myswap6 a1 >  puts " #{a1}" #21 > > What magic is reverse! using, and how can I avail myself of it? > > -- > Posted via http://www.ruby-forum.com/. > >