From: Rick DeNatale Date: 2006-08-26T02:32:24+09:00 Subject: Re: That's Ruby, Virginia! On 8/24/06, Morton Goldberg 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. > > > #! /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 > > > > ["a", "s", "d"] > 0...3 => asd > > > 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 # (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/