Thanks. You've cleared up my confusion as to why array_101 accepts an  
array as a receiver in irb.  Since it gets added as public method of  
Kernel, it appears as a public method of _every_ class in irb. I  
think that's evil enough to be regarded as a bug.

Regards, Morton

On Aug 25, 2006, at 1:32 PM, Rick DeNatale wrote:

> On 8/24/06, Morton Goldberg <m_goldberg / ameritech.net> wrote:
>> Your code only works in irb. You get an error, as you should, if you
>> run it 'real' Ruby.
>> In irb  'array_101' gets added to Array. That's the only reason
>> 'a.array_101' doesn't produce an error. In "real" Ruby, the following
>> produces your result, as it should.
>>
>> <code>
>> #! /usr/bin/ruby -w
>>
>> class Array
>>     def array_101
>>        for i in [0...length]
>>           p self[i] ### prints the array because i = 0...length,  
>> not 0.
>>           puts "#{i} => #{self[i]}"
>>        end
>>     end
>> end
>>
>> a = %w[a s d]
>>
>> a.array_101
>> </code>
>>
>> <result>
>> ["a", "s", "d"]
>> 0...3 => asd
>> </result>
>>
>> The only thing I don't understand is why 'array_101' gets added to
>> Array in irb.
>
> It doesn't it gets added to the Kernel module, just like in real Ruby.
>
> The difference is that in irb, it's a public method and in real Ruby
> it's private, I think that this came up in another context in the past
> few days.
>
> == file array_101.rb ==
> def array_101
>        for i in [0..self.length]
>                puts "#{i} => #{self[i]}"
>        end
> end
>
> a = ['a', 's', 'd']
> p a
> p a.array_101
>
> class X
> end
>
> p X.new.array_101
> === end of file array101.rb===
> $ ruby array101.rb
> ["a", "s", "d"]
> array101.rb:9: private method `array_101' called for ["a", "s",
> "d"]:Array (NoMethodError)
>
> but change the file to wrap the method in the Kernel module
> module Kernel
>    def array_101
>       ...
>    end
> end
>
> $ ruby array101.rb
> ["a", "s", "d"]
> 0..3 => asd
> [0..3]
> array101.rb:3:in `array_101': undefined method `length' for
> #<X:0xb7e1f7b4> (NoMethodError)
>        from array101.rb:16
>
> Note that we are getting through a.array_101, but now we blow up on
> X.new.array_101, but INSIDE the array_101 method, because since it's
> in Kernel, and class Object includes Kernel, makes it available to ALL
> objects.
>
> -- 
> Rick DeNatale
>
> My blog on Ruby
> http://talklikeaduck.denhaven2.com/
>
> IPMS/USA Region 12 Coordinator
> http://ipmsr12.denhaven2.com/
>
> Visit the Project Mercury Wiki Site
> http://www.mercuryspacecraft.com/
>