From: Josh Cheek Date: 2011-01-18T21:11:15+09:00 Subject: Re: Calling by Reference - Two Questions --0016361e847cf354d9049a1dcb78 Content-Type: text/plain; charset=ISO-8859-1 On Mon, Jan 17, 2011 at 6:07 PM, Mike Stephens wrote: > > 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 > > You actually can (though I'm not sure what you think is happening when you say self=a3, so maybe it is not exactly the same): ary = [1,2] def ary.swap new_contents = [ self[1] , self[0] ] replace new_contents end ary # => [1, 2] ary.swap ary # => [2, 1] ary replaced its contents with new_contents 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? > > It is written in C, the core being (at least for 1.8): p1 = RARRAY(ary)->ptr; p2 = p1 + RARRAY(ary)->len - 1; /* points last item */ while (p1 < p2) { tmp = *p1; *p1++ = *p2; *p2-- = tmp; } You could replicate it in Ruby like this: ary = [1,2,3,4] def ary.my_reverse lower , higher = 0 , size-1 while lower < higher self[lower] , self[higher] = self[higher] , self[lower] lower += 1 higher -= 1 end self end ary.my_reverse # => [4, 3, 2, 1] ary.my_reverse # => [1, 2, 3, 4] ary << 5 ary.my_reverse # => [5, 4, 3, 2, 1] ary.my_reverse # => [1, 2, 3, 4, 5] --0016361e847cf354d9049a1dcb78--