On Tue, Jan 18, 2011 at 2:06 PM, Mike Stephens <rubfor / recitel.net> wrote:
> Josh Cheek wrote
>> def ary.swap
>> new_contents = [ self[1] , self[0] ]
>> replace new_contents
>> end
>
> That kind of just moves the question on to how does replace work. But
> thank you for showing me replace, and even more for opening my eyes to
> an exciting world of singletons.
>
>>
>> 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
>>
> That does work (and doesn't need the last self).

The last "self" is the method's return value.  It makes perfect sense
to return self here to have a defined return value and not leak some
implementation state.  Btw, one could do

class Array
  def my_reverse
    (size / 2).times do |i|
      j = size - 1 - i
      self[i], self[j] = self[j], self[i]
    end

    self
  end
end

> It seems to agree with
> the Jesus rule, that you can assign to self but only
> component-by-component.

You cannot assign to self!

14:15:00 ~$ ruby19 -e 'self = 1'
-e:1: Can't change the value of self
self = 1
      ^
14:15:03 ~$

Calling self#[]= is something different - this is actually a method
that must be implemented for the object that self points to.

Kind regards

robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/